BFS 查找源 S 和多个目的地之间的所有最短路径

问题描述

我有一个算法可以在不经过 N 中的顶点的情况下找到源 S 和目标 D 之间的路径。现在我想修改算法以找到源 S 和多个目标之间的所有最短路径。

# Python implementation to find the
# shortest path in the graph using
# dictionaries

# Function to find the shortest
# path between two nodes of a graph
def BFS_SP(graph,start,goal,N):
    explored = []
    
    # Queue for traversing the
    # graph in the BFS
    queue = [[start]]
    
    # If the desired node is
    # reached
    if start == goal:
        print("Same Node")
        return []
    
    # Loop to traverse the graph
    # with the help of the queue
    while queue:
        path = queue.pop(0)
        node = path[-1]
        
        # Condition to check if the
        # current node is not visited
        if node not in explored and node not in N:
            neighbours = graph.edges[node]
            
            # Loop to iterate over the
            # neighbours of the node
            for neighbour in neighbours:
                new_path = list(path)
                new_path.append(neighbour)
                queue.append(new_path)
                
                # Condition to check if the
                # neighbour node is the goal
                if neighbour == goal:
                    print("Shortest path = ",new_path)
                    return new_path
            explored.append(node)

    # Condition when the nodes
    # are not connected
    print("So sorry,but a connecting"\
                "path doesn't exist :(")
    return []


#BFS_SP(graph,'A','D')

解决方法

你只需要改变你的条件“如果邻居==目标:”。当您到达该行时,您已经拥有“邻居”的最短路径,即“new_path”,并且不要忘记在开头添加条件以在目标是源时打印最短路径。