← back to algorithms

Shortest Paths

Nievergelt & Hinrichs · Ch. 7 · Algorithms and Data Structures

Dijkstra finds shortest paths from one source with non-negative weights in O((V+E) log V). Bellman-Ford handles negative edges in O(VE). Floyd-Warshall finds all-pairs shortest paths in O(V³).

10 6 2 3 1 4 7 5 S B T A C D Shortest S-T path: S-A-C-T, cost 8 Direct S-B-T costs 16

Dijkstra's algorithm

Maintain a priority queue of vertices by tentative distance. Extract the minimum, relax its neighbors. Greedy: once a vertex is finalized, its distance is optimal. Requires non-negative weights.

Scheme

Bellman-Ford

Relax all edges V-1 times. Handles negative weights. Detects negative cycles on the V-th pass. O(VE).

Floyd-Warshall

All-pairs shortest paths. Three nested loops: for each intermediate vertex k, for each pair (i,j), check if going through k is shorter. O(V³).

Neighbors

Cross-references