我找到了使用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
用法示例:
graph = {'A': set(['B', 'C']),
'B': set(['A', 'D', 'E']),
'C': set(['A', 'F']),
'D': set(['B']),
'E': set(['B', 'F']),
'F': set(['C', 'E'])}
shortest_path(graph, 'A', 'F') # ['A', 'C', 'F']
答案 0 :(得分:2)
试试这个。它包括一个访问集。我还将变量名'next'修改为'node',因为它是内置函数
def bfs_paths(graph, start, goal):
visited = set()
queue = [(start, [start])]
while queue:
vertex, path = queue.pop(0)
visited.add(vertex)
for node in graph[vertex]:
if node in visited:
continue
elif node == goal:
yield path + [node]
else:
queue.append((node, path + [node]))
def shortest_path(graph, start, goal):
try:
return next(bfs_paths(graph, start, goal))
except StopIteration:
return None