Breadth First Search time complexity analysis

后端 未结 6 1579
说谎
说谎 2020-12-12 16:31

The time complexity to go over each adjacent edge of a vertex is, say, O(N), where N is number of adjacent edges. So, for V numbers of

6条回答
  •  鱼传尺愫
    2020-12-12 17:05

    Considering the following Graph we see how the time complexity is O(|V|+|E|) but not O(V*E).

    enter image description here

    Adjacency List

    V     E
    v0:{v1,v2} 
    v1:{v3}
    v2:{v3}
    v3:{}
    

    Operating How BFS Works Step by Step

    Step1:

    Adjacency lists:

    V     E
    v0: {v1,v2} mark, enqueue v0
    v1: {v3}
    v2: {v3}
    v3: {}
    

    Step2:

    Adjacency lists:

    V     E
    v0: {v1,v2} dequeue v0;mark, enqueue v1,v2
    v1: {v3}
    v2: {v3}
    v3: {}
    

    Step3:

    Adjacency lists:

    V     E
    v0: {v1,v2}
    v1: {v3} dequeue v1; mark,enqueue v3
    v2: {v3}
    v3: {}
    

    Step4:

    Adjacency lists:

    V     E
    v0: {v1,v2}
    v1: {v3}
    v2: {v3} dequeue v2, check its adjacency list (v3 already marked)
    v3: {}
    

    Step5:

    Adjacency lists:

    V     E
    v0: {v1,v2}
    v1: {v3}
    v2: {v3}
    v3: {} dequeue v3; check its adjacency list
    

    Step6:

    Adjacency lists:

    V     E
    v0: {v1,v2} |E0|=2
    v1: {v3}    |E1|=1
    v2: {v3}    |E2|=1
    v3: {}      |E3|=0
    

    Total number of steps:

    |V| + |E0| + |E1| + |E2| +|E3| == |V|+|E|
     4  +  2   +  1   +   1  + 0   ==  4 + 4
                               8   ==  8
    

    Assume an adjacency list representation, V is the number of vertices, E the number of edges.

    Each vertex is enqueued and dequeued at most once.

    Scanning for all adjacent vertices takes O(|E|) time, since sum of lengths of adjacency lists is |E|.

    Hence The Time Complexity of BFS Gives a O(|V|+|E|) time complexity.

提交回复
热议问题