简体   繁体   中英

Time complexity of DFS in undirected graph

Lets say we have 4 nodes and all nodes are connected to all other nodes, and I need to go from node1 to node4. Most resources i check the time complexity is O(V+E) , but I am kind of confused.

                            node1 
                              |
         node2      /       node3       /        node4     level2     3
           | 
  node1 / node3 / node4      ..................            level3     3 to power of 2

so complexity is N to the power of N if all node will be visited. Even using a hashset to keep track of which nodes have been visited using backtracking, it should not impact the overall time complexity?

The complexity would not be N N if you visit all nodes from each node, it would be N 2 , if N here is your number of nodes.

Now it so happens that a complete graph (a graph where all nodes are connected to all nodes, like in your example) has a number of edges |E| = O(|V| 2 ) . If you don't know why, just note that each node is connected to (N - 1) other nodes so the exact number of edges is (N - 1) 2 = N 2 - 2N + 1 = O(N 2 ) .

The time complexity of Depth-first search is, like you say, O(|V| + |E|) . In big-O notation, this is just the same as O(max(|V|, |E|)) , because only the dominant term will matter. So for our complete graph, |E| dominates and the complexity is just O(|E|) .

As we previously stated, |E| = O(|V| 2 ) , so our complexity is O(|E|) = O(|V| 2 ) .

Does this provide some clarity to your confusion?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM