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?
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.
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.
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With