![](/img/trans.png)
[英]Is it possible to traverse all connected nodes in a graph with DFS when cycles are present?
[英]Graph recursive DFS when cycles exist?
我對在存在循環的無向(或有向)圖中處理 DFS 很感興趣,因此進入無限循環的風險並不小。
注意:這個問題不是關於 LeetCode 上的循環檢測問題。 下面是一種迭代方法:
g = {'a':['b','c'],
'b':['a','f'],
'c':['a','f','d'],
'd':['c','e'],
'e':['d'],
'f':['c','b'],
'g':['h'],
'h':['g']
}
def dfs(graph, node, destination):
stack = [node]
visited = []
while stack:
current = stack.pop()
if current == destination:
return True
visited.append(current)
next_nodes = list(filter(lambda x: x not in visited + stack, graph[current]))
stack.extend(next_nodes)
return False
dfs(g,'h', 'g')
>>> True
dfs(g,'a', 'g')
>>> False
我的問題是,這樣的遞歸方法是否存在? 如果是這樣,如何在python中定義它?
如果您對檢測是否存在任何循環不感興趣,而只是對避免無限循環(如果有)感興趣,那么類似以下遞歸實現的方法對您有用:
def dfs(graph, node, destination, visited=None):
if visited is None:
visited = set()
if node == destination:
return True
visited.add(node)
return any(
dfs(graph, neighbor, destination, visited=visited)
for neighbor in graph[node]
if neighbor not in visited
)
請注意,在any
中使用了生成器表達式,因此它以惰性方式(一個接一個)進行評估,並且一旦解決方案(即到目的地的路徑)出現,整個any(...)
表達式就會盡早返回True
在沒有檢查其他鄰居和路徑的情況下找到,因此不會進行額外的遞歸調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.