简体   繁体   English

无向图中 DFS 的时间复杂度

[英]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.假设我们有 4 个节点,所有节点都连接到所有其他节点,我需要从 node1 到 node4 的 go。 Most resources i check the time complexity is O(V+E) , but I am kind of confused.我检查的大多数资源的时间复杂度是O(V+E) ,但我有点困惑。

                            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.因此,如果所有节点都将被访问,那么复杂度是 N 的 N 次方。 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.如果您从每个节点访问所有节点,复杂性不会是N N ,如果N是您的节点数,那么复杂性将是N 2

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|现在碰巧一个完整的图(一个所有节点都连接到所有节点的图,就像在你的例子中一样)有许多边|E| = O(|V| 2 ) . = 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 ) .如果您不知道为什么,请注意每个节点都连接到(N - 1)个其他节点,因此确切的边数是(N - 1) 2 = N 2 - 2N + 1 = O(N 2 )

The time complexity of Depth-first search is, like you say, O(|V| + |E|) .正如你所说,深度优先搜索的时间复杂度是O(|V| + |E|) In big-O notation, this is just the same as O(max(|V|, |E|)) , because only the dominant term will matter.在大 O 表示法中,这与O(max(|V|, |E|))相同,因为只有主导项才重要。 So for our complete graph, |E|所以对于我们的完整图, |E| dominates and the complexity is just O(|E|) .占主导地位,复杂性仅为O(|E|)

As we previously stated, |E|正如我们之前所说, |E| = O(|V| 2 ) , so our complexity is O(|E|) = O(|V| 2 ) . = O(|V| 2 ) ,所以我们的复杂度是O(|E|) = O(|V| 2 )

Does this provide some clarity to your confusion?这是否为您的困惑提供了一些清晰的信息?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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