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

BFS to find all shortest paths between source S and multiple destination

我有一个算法可以在不经过 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')

你只需要改变你的条件“if neighbor == goal:”。当你到达那条线时,你已经有了“邻居”的最短路径,即“new_path”并且不要忘记在开始时添加条件以在目标为源时打印最短路径。