Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Breadth First Search time complexity analysis

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 vertices the time complexity becomes O(V*N) = O(E), where E is the total number of edges in the graph. Since removing and adding a vertex from/to a queue is O(1), why is it added to the overall time complexity of BFS as O(V+E)?

like image 861
Meena Chaudhary Avatar asked Oct 24 '14 13:10

Meena Chaudhary


People also ask

What is the complexity of BFS and DFS?

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.

Which time and space complexity is BFS?

BFS: Time complexity is O(|V|) , where |V| is the number of nodes. You need to traverse all nodes. Space complexity is O(|V|) as well - since at worst case you need to hold all vertices in the queue.

Why is time complexity of BFS O v E?

In this notation, the E is the total number of edges in the graph. 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.

Does BFS run in linear time?

Answer is no. It will take O(V) time(more accurately θ(V)). Even if Adj[v] is empty, running the line where you check Adj[v] will itself take some constant time for each vertex. So running time of BFS is O(V+E) which means O(max(V,E)).


1 Answers

I hope this is helpful to anybody having trouble understanding computational time complexity for Breadth First Search a.k.a BFS.

Queue graphTraversal.add(firstVertex);  // This while loop will run V times, where V is total number of vertices in graph. while(graphTraversal.isEmpty == false)      currentVertex = graphTraversal.getVertex();      // This while loop will run Eaj times, where Eaj is number of adjacent edges to current vertex.     while(currentVertex.hasAdjacentVertices)         graphTraversal.add(adjacentVertex);      graphTraversal.remove(currentVertex); 

Time complexity is as follows:

V * (O(1) + O(Eaj) + O(1)) V + V * Eaj + V 2V + E(total number of edges in graph) V + E 

I have tried to simplify the code and complexity computation but still if you have any questions let me know.

like image 189
Meena Chaudhary Avatar answered Oct 14 '22 18:10

Meena Chaudhary