Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the time complexity of DFS and BFS depend on the way the graph is represented?

Tags:

The site http://web.eecs.utk.edu/~huangj/CS302S04/notes/graph-searching.html describes that when an adjacency list is used then, DFS and BFS have complexity O(V+E), and if an adjacency matrix is used, the complexity is O(V2). Why is this?

like image 317
Nitish Jain Avatar asked May 29 '14 02:05

Nitish Jain


People also ask

How is time complexity of BFS impacted by graph representation?

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.

Why BFS and DFS have same time complexity?

In BFS, the space complexity is more critical as compared to time complexity. DFS has lesser space complexity because at a time it needs to store only a single path from the root to the leaf node. 17. BFS is slow as compared to DFS.

What is the time complexity of graph traversal for DFS and 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 is used in DFS?

The time complexity of DFS if the entire tree is traversed is O ( V ) O(V) O(V) where V is the number of nodes. In the case of a graph, the time complexity is O ( V + E ) O(V + E) O(V+E) where V is the number of vertexes and E is the number of edges.


1 Answers

In both cases, the runtime depends on how long it takes to iterate across the outgoing edges of a given node. With an adjacency list, the runtime is directly proportional to the number of outgoing edges. Since each node is visited once, the cost is the number of nodes plus the number of edges, which is O(m + n). With am adjacency matrix, the time required to find all outgoing edges is O(n) because all n columns in the row for a node must be inspected. Summing up across all n nodes, this works out to O(n2).

Hope this helps!

like image 126
templatetypedef Avatar answered Oct 12 '22 11:10

templatetypedef