Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the complexity of BFS O(V+E) instead of O(V*E)?

Some pseudocode here (disregard my style)

Starting from v1(enqueued):

function BFS(queue Q)
  v2 = dequeue Q
  enqueue all unvisited connected nodes of v2 into Q
  BFS(Q)
end // maybe minor problems here

Since there are V vertices in the graph, and these V vertices are connected to E edges, and visiting getting connected nodes (equivalent to visiting connected edges) is in the inner loop (the outer loop is the recursion itself), it seems to me that the complexity should be O(V*E) rather than O(V+E). Can anyone explain this for me?

like image 668
OneZero Avatar asked Sep 04 '13 03:09

OneZero


People also ask

What is the complexity of BFS?

Time Complexity of BFS = O(V+E) where V is vertices and E is edges. Time Complexity of DFS is also O(V+E) where V is vertices and E is edges.

Why time complexity of graph is V E?

It's O(V+E) because each visit to v of V must visit each e of E where |e| <= V-1. Since there are V visits to v of V then that is O(V). Now you have to add V * |e| = E => O(E). So total time complexity is O(V + E).

Why does BFS algorithm take ove time?

Time complexity to go over each adjacent edges of a vertex is say O(N) , where N is number of adjacent edges. So for V number of vertices time complexity becomes O(V*N) = O(E) , where E is the total number of edges in the graph.


1 Answers

E is not the number of edges adjacent to each vertex - its actually the total number of edges in the graph. Defining it this way is useful because you don't necessarily have the same number of edges on every single vertex.

Since each edge gets visited once by the time the DFS ends, you get O(E) complexity from that part. Then you add the O(V) for visiting each vertex once and get O(V + E) on total.

like image 129
hugomg Avatar answered Sep 20 '22 19:09

hugomg