![](/img/trans.png)
[英]Time complexity of DFS on graph (O(V+E)) vs DFS on matrix (3^(M*N))
[英]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:
因此,没有顶点被访问超过 1 次,并且
for neighbour in graph[node]:
因此,连接到每个节点的每条边都被认为是DFS的一个可能步骤
所以 O(V+E) 的时间复杂度(假设在你的集合中插入和删除 O(1))
除了第一次调用dfs
之外,其他所有dfs
调用都将唯一地对应一个边。 由于visited
机制,不可能对node
和neighbor
的相同值进行dfs
的递归调用。
实际上这是该算法的唯一决定因素,因此它是 O(E)。
如果图断开连接,该算法将不会访问所有节点。 当这是必须处理的情况时,驱动程序代码应如下所示:
for node in graph:
dfs(visited, graph, node)
随着这种变化,复杂度变为 O(V+E)。 这是因为在断开连接的图中,节点可能比边多得多,因此 O(E) 无法捕获复杂性,驱动程序代码中的循环成为决定因素。 因此,您会说它是 O(MAX(V, E)),与 O(V+E) 相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.