问题描述
使用下面的BFS实现,我们如何修改程序以存储从开始到结束节点的所有路径?有什么想法吗?
def bfs(graph_to_search,start,end):
queue = [[start]]
visited = set()
while queue:
# Gets the first path in the queue
path = queue.pop(0)
# Gets the last node in the path
vertex = path[-1]
# Checks if we got to the end
if vertex == end:
return path
# We check if the current node is already in the visited nodes set in order not to recheck it
elif vertex not in visited:
# enumerate all adjacent nodes,construct a new path and push it into the queue
for current_neighbour in graph_to_search.get(vertex,[]):
new_path = list(path)
new_path.append(current_neighbour)
queue.append(new_path)
# Mark the vertex as visited
visited.add(vertex)
解决方法
也许类似的事情可能起作用。我认为,在检查是否访问了某个节点时,您会从结果中排除许多路径,这仅仅是因为它们包含相同的节点。我将其更改为将整个路径添加到已访问,然后改为选中此路径。同样,创建一个空列表results
,如果找到最后一个节点,我们会附加该列表。您的代码将在找到最后一个节点的那一刻从函数中返回,并且不会浏览并找到剩余的路径。让我知道这是否有效!
def bfs(graph_to_search,start,end):
queue = [[start]]
visited = set()
results = []
while queue:
# Gets the first path in the queue
path = queue.pop(0)
# Gets the last node in the path
vertex = path[-1]
# Checks if we got to the end
if vertex == end:
results.append(path)
continue
# We check if the current path is already in the visited nodes set in order not to recheck it
elif path not in visited:
# enumerate all adjacent nodes,construct a new path and push it into the queue
for current_neighbour in graph_to_search.get(vertex,[]):
new_path = path.copy()
new_path.append(current_neighbour)
queue.append(new_path)
# Mark the vertex as visited
visited.add(path)
return results
您还可以将queue
中的元素另存为包含当前顶点和先前路径的元组,如下所示。可能更具可读性。
queue = [(start,[])]
vertex,path = queue.pop(0)