[英]Finding cycle in graph using DFS - recursion problem
我试图制作一个在无向图中搜索循环的算法,但似乎 return 语句不起作用。
def wrapped_dfs_recursive(G: Dict[int, List[int]], current_vertex: int, parent: int, visited: List[int] = None):
for neighbour in G[current_vertex]:
if neighbour in visited and neighbour != parent:
print("Found cycle")
return True
visited.append(current_vertex)
if current_vertex in G.keys():
for vertex in G[current_vertex]:
if vertex not in visited:
wrapped_dfs_recursive(G, current_vertex=vertex, parent=current_vertex, visited=visited)
else:
return None
return False
当我为一个简单的循环图执行此代码时,它返回 False,但它还会两次打印消息“找到循环”。 那么如果它执行打印 function 为什么它不返回 True? 我的停止条件有什么问题吗?
好的,我发现了问题。 我在调用 Wrapped_dfs_recursive() 时错过了“返回”这个词,所以它没有改变任何东西,最后返回了 False。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.