23

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?

OneZero
  • 11,556
  • 15
  • 55
  • 92
  • 1
    Very simplified without much formality: every edgy is considered exactly twice, and every node is processed exactly once, so the complexity has to be a constant multiple of the number of edges as well as the number of vertices. – G. Bach Sep 04 '13 at 04:06
  • This includes having a mechanism to avoid cycles – Khaled.K Sep 04 '13 at 05:27

1 Answers1

23

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.

hugomg
  • 68,213
  • 24
  • 160
  • 246
  • 8
    Your answer is a bit more general - it can be related to both depth-first search (DFS) and breadth-first search (BFS). Maybe that's why you mispelled BFS as DFS in your answer (note the question was asking for BFS). – yasen Sep 04 '13 at 04:38
  • Why even bother to write time complexity as O(V+E) if the number of edges to a vertex is different each time the vertex's neighbors are visited? – Sandeep May 27 '21 at 13:24
  • In this notation, the E is the total number of edges in the graph. – hugomg May 27 '21 at 13:26
  • if the graph is represented in adjacency matrix then time complexity would be O(V*V) right? Because each time we pop the vertex from the q, we have to traverse all the vertex to find the adjacency vertex. – Ujesh Nada Jan 23 '22 at 10:04