Shortest paths
With equal edge weights use BFS. With non-negative weights use Dijkstra: always settle the closest unsettled vertex, using a min-heap. With negative weights use Bellman-Ford, n - 1 rounds of relaxing every edge, which also detects negative cycles. For all pairs on small graphs, Floyd-Warshall tries every vertex as a stop. Many puzzles are shortest paths on a graph of states.
How to recognise it
- The fewest steps, the cheapest cost or the smallest effort.
- Weights that are all 1, all non-negative, or sometimes negative.
- States like jug contents, words or board squares, joined by moves.
Choosing the algorithm
| Weights | Algorithm | Time |
|---|---|---|
| all equal | BFS | O(V + E) |
| 0 or 1 | 0-1 BFS (deque) | O(V + E) |
| non-negative | Dijkstra (min-heap) | O(E log V) |
| any, single source | Bellman-Ford | O(V E) |
| DAG | relax in topological order | O(V + E) |
| all pairs, small V | Floyd-Warshall | O(V³) |
dijkstra(s): dist[s] = 0; heap = [(0, s)]
while heap: (d, u) = pop; if d > dist[u]: skip
for (v, w): if d + w < dist[v]: dist[v] = d + w; push (dist[v], v)
Vertices, edges, adjacency lists and the other words used here are on the Structures page.
Variations
- Count shortest paths: add counts on equal distances, reset on strictly shorter ones.
- Limited stops: Bellman-Ford rounds, or BFS by number of edges.
- Minimum effort: Dijkstra where a path costs its largest step, not its sum.
- Print the path: remember each vertex's parent and walk back.
Common mistakes
- Using Dijkstra with negative weights.
- Not skipping stale heap entries.
Problems
- Shortest path in DAGmediumguide ready
- Shortest path in undirected graph with unit weightsmediumguide ready
- Dijkstra's algorithmmediumguide ready
- Print Shortest Pathmediumguide ready
- Shortest Path in Binary Matrixmediumguide ready
- Path With Minimum Effortmediumguide ready
- Cheapest Flights Within K Stopsmediumguide ready
- Minimum multiplications to reach endmediumguide ready
- Number of Ways to Arrive at Destinationmediumguide ready
- Bellman ford algorithmmediumguide ready
- Floyd warshall algorithmmediumguide ready
- Find the City With the Smallest Number of Neighbors at a Threshold Distancemediumguide ready
- Snakes and Laddersmediumguide ready
- Detect Negative cycle in a graphmediumguide ready
- Water Jug problem using BFSmediumguide ready
- Minimum edges to reverse o make path from source to destinationmediumguide ready
- Word Ladderhardguide ready
- Word Ladder IIhardguide ready