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

python中非加权图的BFS算法

如何解决python中非加权图的BFS算法

我在执行它时遇到了麻烦。可以说我的主要顶点为“ 1”,我希望它向我显示我的主要顶点和图形中其他所有顶点之间的最快路径。但是我唯一知道的方法就是调用BFS n次(n-图中其他顶点的数量),因此它的时间复杂度非常差。一次运行BFS后如何获取这些数据?

假设这是我的 graph

正确的输出here(输入线为绿色)

这是我的代码

# finds shortest path between 2 nodes of a graph using BFS
def bfs_shortest_path(graph,start,goal):
    # keep track of explored nodes
    explored = []
    # keep track of all the paths to be checked
    queue = [[start]]

    # keeps looping until all possible paths have been checked
    while queue:
        # pop the first path from the queue
        path = queue.pop(0)
        # get the last node from the path
        node = path[-1]

        if node not in explored:
            neighbours = graph[node]

            # go through all neighbour nodes,construct a new path and
            # push it into the queue
            for neighbour in neighbours:
                new_path = list(path)
                new_path.append(neighbour)
                queue.append(new_path)

                # return path if neighbour is goal
                if neighbour == goal:
                    return new_path

            # mark node as explored
            explored.append(node)


if __name__ == '__main__':
    # creating a graph from input data
    N = int(input().strip())

    graph = {x: [] for x in range(1,N + 1)}
    for i in range(N - 1):
        start,end = [int(x) for x in input().split(' ')]
        graph[start].append(end)
        graph[end].append(start)

    # calculating fastest paths for every vertex (1 - starting vertex for all
    for i in range(2,N + 1):
        print(f"Shortest path between 1 and {i} is: ",bfs_shortest_path(graph,1,i))

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