Search code examples
algorithmgraph-theorypath-findingweighted-graph

Multiple source and multiple target shortest path problem


I'm trying to figure out the most optimal way to get the shortest paths from all the source nodes to any one of the target nodes that leads to the minimum weight in a weighted graph. All nodes are either a source node or a target node. So figure we have a graph consisting of A, B, C as source nodes and D, E, F as target nodes. A, B, C has to find the shortest path to any one of the target nodes that happens to have the shortest path.

The naive solution is to use the Dijkstra's algorithm or something similar to first find the shortest path from A to D and then from A to E etc. and then comparing the final weight of each of those shortest paths to see which is actually the shortest. I want to know if there is a more efficient solution to this.


Solution

  • Add a new node that leads to all the sources (make these new edges 0-weight), and run Dijkstra's from the new node.