我正在用BFS寻找最短路径,我很快就得到了这个RecursionError: maximum recursion depth exceeded in comparison
,有什么建议可以用生成器避免它?或者让它迭代是唯一的好选择?在
代码如下:
def bfs_paths(graph, start, goal):
queue = [(start, [start])]
while queue:
(vertex, path) = queue.pop(0)
for next in graph[vertex] - set(path):
if next == goal:
yield path + [next]
else:
queue.append((next, path + [next]))
def shortest_path(graph, start, goal):
try:
return next(bfs_paths(graph, start, goal))
except StopIteration:
return None
使用示例:
^{pr2}$
试试这个。它包括一个参观的集合。我还修改了“node”的变量名“next”,因为它是一个内置函数
相关问题 更多 >
编程相关推荐