微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用BFS查找从起点到终点的所有路径

如何解决使用BFS查找从起点到终点的所有路径

使用下面的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)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。