[英]How does time complexity for depth first search on a graph come out to be O(V+E) in the following code?
How does time complexity for depth first search on a graph come out to be O(V+E) in the following code?在以下代码中,图上深度优先搜索的时间复杂度如何变为 O(V+E)?
Using a Python dictionary to act as an adjacency list
graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}
visited = set() # Set to keep track of visited nodes.
def dfs(visited, graph, node):
if node not in visited:
print (node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
# Driver Code
dfs(visited, graph, 'A')
if node not in visited:
due to this, no vertex is visited more than 1 time, and因此,没有顶点被访问超过 1 次,并且
for neighbour in graph[node]:
due to this every edge connected to each node is considered as a possible step of DFS因此,连接到每个节点的每条边都被认为是DFS的一个可能步骤
so the time complexity of O(V+E) (assuming O(1) insertion and deletion in your set)所以 O(V+E) 的时间复杂度(假设在你的集合中插入和删除 O(1))
Except for the first call of dfs
, every other call of dfs
will uniquely correspond to one edge.除了第一次调用
dfs
之外,其他所有dfs
调用都将唯一地对应一个边。 Because of the visited
mechanism, it is not possible that for the same value of node
and neighbor
the recursive call of dfs
is made.由于
visited
机制,不可能对node
和neighbor
的相同值进行dfs
的递归调用。
Actually this is the only determining factor for this algorithm, and so it is O(E).实际上这是该算法的唯一决定因素,因此它是 O(E)。
In case the graph is disconnected, this algorithm will not visit all nodes.如果图断开连接,该算法将不会访问所有节点。 When that is a case that must be dealt with, the driver code should look like this:
当这是必须处理的情况时,驱动程序代码应如下所示:
for node in graph:
dfs(visited, graph, node)
With this change the complexity becomes O(V+E).随着这种变化,复杂度变为 O(V+E)。 This is because there might be more many more nodes than edges in a disconnected graph, and so O(E) would not capture the complexity, and the loop in the driver code becomes the determining factor.
这是因为在断开连接的图中,节点可能比边多得多,因此 O(E) 无法捕获复杂性,驱动程序代码中的循环成为决定因素。 Yould thus say it is O(MAX(V, E)), which is the same as O(V+E).
因此,您会说它是 O(MAX(V, E)),与 O(V+E) 相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.