Single-Source Shortest Path (SSSP)
Given a source vertex , compute shortest distances from to every vertex .
Pick the Right Algorithm
Unweighted graph
- Use BFS.
- Time: .
Nonnegative edge weights
- Use Dijkstra.
- Time: with binary heap.
Negative edge weights allowed
- Use Bellman-Ford.
- Time: .
- Also detects reachable negative cycles.
DAG
- Topological-order DP.
- Time: .
Relaxation Principle
For an edge , try:
All shortest-path algorithms differ mainly in the order and number of relaxations.
Output Variants
- Distance only
- Distance + predecessor array (
parent) to reconstruct actual shortest paths
Multi-Source Shortest Path
Compute shortest distance from a set of sources to every vertex.
Equivalent definition:
Core Trick: Super Source
Add a new node and connect it to each source with edge weight . Then run a single-source algorithm from .
Cases
Unweighted graph
- Initialize BFS queue with all sources at distance .
- Time: .
Nonnegative weighted graph
- Initialize priority queue with all sources at distance (or use super source + Dijkstra).
- Time: .
Negative edges
- Use super source + Bellman-Ford.
Relation to All-Pairs Shortest Paths (APSP)
- Multi-source: one run for a source set .
- APSP: run SSSP from every vertex (or use Floyd-Warshall).
TIP
If you need distances to the nearest facility (hospital, station, server), multi-source shortest path is usually the right model.