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 (将#修改为@)