gpt4 book ai didi

python - 将深度优先算法从递归更改为迭代

转载 作者:行者123 更新时间:2023-12-01 03:30:45 26 4
gpt4 key购买 nike

我正在尝试找出一种方法,使用某种形式的循环将函数 helper 从递归转换为迭代。

我现在真的很困惑,我想知道你们是否可以提供帮助。它是一个创建的函数,用于使用深度优先遍历来搜索给定的起点和终点路径是否存在于有向图中。

def helper(graph, current, visited):
if current in graph:
for neighbor in graph[current]:
if neighbor not in visited:
visited.append( neighbor )
helper(graph, neighbor, visited)

def DFS(graph, start, goal):
if start not in graph and goal not in graph:
return False
visited = [start]
helper(graph, start, visited)
return goal in visited

最佳答案

解决方案是使用显式堆栈:

stack = [start]
while len(stack) > 0:
node = stack.pop()
for x in graph[node]:
if x not in visited:
visited.add(x)
stack.append(x)

作为旁注,您的代码正在使用访问列表,这将使事情O(n^2)变慢,您可以使用集合 相反。此外,如果您在搜索中只需要进行存在/缺席检查,那么您可以在找到目标后立即退出。

关于python - 将深度优先算法从递归更改为迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40963247/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com