Shortest Paths: Dijkstra, Bellman–Ford, Floyd–Warshall
The cheapest way from A to B, with and without negative edges.
A phone finds the fastest route across a continent in a fraction of a second, a trading system spots a loop of exchange rates that returns more money than it started with, and a router recomputes its tables after a link fails. All three are shortest-path problems, solved by three algorithms built on one primitive: relax an edge.
What you’ll learn
- Define single-source, single-pair and all-pairs shortest paths, explain edge relaxation and the triangle inequality, and distinguish negative edges from negative cycles.
- Implement Dijkstra's algorithm with a binary heap and lazy deletion, prove that settled distances are final, and state its bound.
- Run Bellman–Ford in , explain why rounds suffice, and detect negative cycles.
- Derive Floyd–Warshall's recurrence, explain why the loop over intermediate vertices must be outermost, and reconstruct paths.
- Choose the right algorithm from the weights and queries of a problem, and avoid the classic bugs.
Distances, relaxation and the triangle inequality
Take a directed graph with edge weights . The weight of a path is the sum of its edge weights, and the distance is the smallest weight of a path from to , or if there is none. A shortest-path problem comes in three shapes: single pair ( to ), single source (SSSP: to every vertex) and all pairs (APSP). No known algorithm solves the single-pair problem asymptotically faster in the worst case than single source, so that is where the algorithms start.
Every algorithm here keeps an estimate and improves it with one primitive, relaxation:
Negative edges versus negative cycles. Negative weights are fine in themselves: they model gains, refunds or rewards. What breaks the problem is a negative cycle reachable from : going around it again and again drives the cost to , so distances beyond it are undefined. Forbidding repeated vertices does not rescue it, because the shortest simple path with negative cycles present is NP-hard.
Think first Why does a single negative edge in an undirected graph already break Bellman–Ford, which handles negative edges in directed graphs?
An undirected edge of weight is two arcs, and . If , the round trip is a negative cycle of weight . Undirected graphs with negative weights need different techniques, based on matching, which is why negative weights appear almost always in directed problems.
Dijkstra’s algorithm: settle the closest vertex
When every weight is non-negative, Dijkstra's algorithm (1959) grows a set of settled vertices whose distances are final. At each step it settles the unsettled vertex with the smallest estimate and relaxes the edges leaving it. A priority queue finds that vertex; with Python's heapq, the simplest correct version pushes a new entry whenever an estimate improves and skips the outdated copies when they surface (lazy deletion).
import heapq
def dijkstra(n, adj, s):
"""adj[u] = [(v, w), ...] with every w >= 0. Returns distances and parents."""
INF = float('inf')
dist, parent = [INF] * n, [-1] * n
dist[s] = 0
heap = [(0, s)]
while heap:
d, u = heapq.heappop(heap)
if d > dist[u]:
continue # stale entry: u was settled with a smaller key
for v, w in adj[u]:
if d + w < dist[v]: # relax u -> v
dist[v], parent[v] = d + w, u
heapq.heappush(heap, (dist[v], v))
return dist, parentEvery edge is relaxed once, from the moment its tail is settled, so the heap receives at most entries and each operation costs : in the worst case. Follow parent back from any vertex to read its path.
Suppose not, and let be the first vertex settled with . Take a shortest path from to , let be its first vertex that is not yet settled, and the vertex before , which is settled and therefore exact:
When was settled, the edge was relaxed, and lies on a shortest path:
Here the weights must be non-negative: the rest of the path, from to , cannot cost less than zero:
So with unsettled, and the heap would have popped before , a contradiction.
Edges: 4, 1, 2, 1, 5, 3, 6, 1, 6. What is the distance from to ?
Show the answer
8
Dijkstra settles (0), (1), (3, through , beating the direct 4), (4), (7) and (8). The shortest path is , five edges, although uses only three.
| Priority queue | Time | Best for |
|---|---|---|
| unsorted array, scanned for the minimum | dense graphs, | |
| binary heap, lazy deletion | almost everything in practice | |
| Fibonacci heap with decrease-key | the theoretical bound (Fredman & Tarjan, 1987) |
#include <cstdio>
#include <functional>
#include <queue>
#include <utility>
#include <vector>
using namespace std;
using ll = long long;
int main() {
int n, m, s;
if (scanf("%d %d %d", &n, &m, &s) != 3) return 0;
vector<vector<pair<int, ll>>> adj(n);
for (int i = 0; i < m; i++) {
int u, v; ll w;
if (scanf("%d %d %lld", &u, &v, &w) != 3) return 0;
adj[u].push_back({v, w}); // add {u, w} to adj[v] too if undirected
}
const ll INF = (ll)1e18; // never added to: only settled distances are
vector<ll> dist(n, INF);
priority_queue<pair<ll, int>, vector<pair<ll, int>>, greater<>> pq; // min-heap
dist[s] = 0;
pq.push({0, s});
while (!pq.empty()) {
auto [d, u] = pq.top();
pq.pop();
if (d > dist[u]) continue; // stale entry
for (auto [v, w] : adj[u])
if (d + w < dist[v]) {
dist[v] = d + w;
pq.push({dist[v], v});
}
}
for (int v = 0; v < n; v++) printf("%lld\n", dist[v] == INF ? -1LL : dist[v]);
}The contest idiom: priority_queue is a max-heap by default, and greater<> makes it a min-heap; long long distances avoid overflow; structured bindings need C++17. Input: , , the source, then lines "u v w" with 0-indexed vertices; unreachable vertices print . On the predict example above it prints the distances 0, 3, 1, 4, 7, 8 for .
Negative edges: Bellman–Ford
The proof used non-negative weights at exactly one point: the rest of a path cannot cost less than zero. Take 2, 4, and 1. Dijkstra's algorithm settles (0), (2), (3) and (4). Relaxing then lowers to 1, but too late: keeps 3, while costs .
Bellman–Ford (Ford 1956, Bellman 1958, Moore 1959) gives up on ordering the vertices and relaxes every edge, times over. After round , is at most the weight of the best path to with at most edges. Without negative cycles some shortest path is simple, with at most edges, so rounds make every distance exact.
def bellman_ford(n, edges, s):
"""edges = [(u, v, w)]. Returns distances, or None if a negative cycle is reachable from s."""
INF = float('inf')
dist = [INF] * n
dist[s] = 0
for _ in range(n - 1): # round i fixes every shortest path with <= i edges
changed = False
for u, v, w in edges:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
changed = True
if not changed:
break # early exit: nothing moved this round
if any(dist[u] + w < dist[v] for u, v, w in edges):
return None # still improvable after n - 1 rounds
return distin the worst case; the early exit helps on many inputs but not on adversarial ones. A queue-based variant that relaxes only the edges out of vertices whose distance just changed (Moore's version, called SPFA in contest circles) is often much faster in practice but keeps the worst case, and test data can be built to reach it.
All pairs: Floyd–Warshall
For all pairs, Dijkstra's algorithm from every vertex costs with non-negative weights. On dense graphs, or with negative edges, Floyd–Warshall (Floyd 1962, building on Warshall 1962 and Roy 1959) is simpler. Number the vertices and let be the length of a shortest path from to whose intermediate vertices all lie in . Such a path either avoids or passes through it exactly once (without negative cycles, a repeat of can be cut out):
def floyd_warshall(n, edges):
INF = float('inf')
d = [[0 if i == j else INF for j in range(n)] for i in range(n)]
nxt = [[j if i == j else None for j in range(n)] for i in range(n)]
for u, v, w in edges:
if w < d[u][v]:
d[u][v], nxt[u][v] = w, v
for k in range(n): # k outermost: allow k as an intermediate vertex
for i in range(n):
if d[i][k] == INF:
continue
for j in range(n):
if d[i][k] + d[k][j] < d[i][j]:
d[i][j] = d[i][k] + d[k][j]
nxt[i][j] = nxt[i][k] # first step toward j now heads toward k
return d, nxt # negative cycle through i <=> d[i][i] < 0
def path(nxt, i, j):
if nxt[i][j] is None:
return []
p = [i]
while i != j:
i = nxt[i][j]
p.append(i)
return p time and memory in three tight loops: for , about simple steps, within a second in C++ by the usual rule of thumb. nxt[i][j] stores the first step of a shortest path from to , so path walks it in .
Replacing by (or, and) turns the same triple loop into Warshall's transitive closure, : which vertices can reach which.
Special cases that beat the general algorithms
The general algorithms pay for their generality. When the weights or the graph have structure, simpler and faster methods apply:
| When | Use | Time |
|---|---|---|
| all weights equal | BFS: distance is the number of edges | |
| weights 0 or 1 | 0-1 BFS: a deque; a vertex reached by a 0-edge goes to the front, by a 1-edge to the back | |
| small integer weights, at most | Dial's bucket queue (1969): one bucket per distance value | |
| a DAG, any weights | relax the edges in topological order | |
| one target, plus a lower bound on the distance still to go | A*: Dijkstra ordered by | depends on ; with a consistent , it expands no more vertices than Dijkstra, up to ties |
Why 0-1 BFS works: at every moment the deque holds vertices whose tentative distances are some value (toward the front) and (toward the back). Popping from the front therefore pops a minimum, exactly as Dijkstra's heap would, but without the logarithm.
A grid has cells. Stepping into an empty cell is free, and stepping into a wall cell (destroying it) costs 1. You want the fewest walls to destroy on the way from one corner to the opposite one. Which algorithm fits best?
- BFS, counting the steps
- Bellman–Ford
- 0-1 BFS with a deque
- Floyd–Warshall
Show the answer
C. 0-1 BFS with a deque
Every move costs 0 or 1, so 0-1 BFS finds the cheapest route in , a few million operations here. Dijkstra's algorithm would also be correct, with an extra logarithmic factor.
Recognizing it
Signals. "Minimum cost, time or distance", "cheapest route", "fastest way to reach every node". Then read the weights: all equal points to BFS, 0 and 1 to 0-1 BFS, non-negative to Dijkstra, negative to Bellman–Ford. Probabilities that multiply become sums under ; "a loop that makes money" is a negative cycle; "all pairs" with up to a few hundred is Floyd–Warshall. Constraints of the form are shortest paths in disguise, a classic of the Optimal lesson on negative weights.
| Problem (in our words) | Key idea | Time |
|---|---|---|
| How long until a signal sent from one node reaches every node? | Dijkstra from the sender; the answer is the largest distance, or "never" if some node is unreachable | |
| Cheapest trip with at most flights | Bellman–Ford for rounds, each relaxing from a copy of the previous round's distances | |
| Most reliable route, where each link succeeds with probability | Dijkstra on weights , or directly maximizing the product | |
| Route whose single steepest climb is as small as possible | Dijkstra with in place of (or binary search on the answer with BFS) | |
| The city with the fewest others within distance , for | Floyd–Warshall, then count per row |
Common bugs.
- Overflow: with 32-bit integers, wraps around to a negative number. Use 64-bit distances, an "infinity" such as that leaves headroom, and never relax out of an unreached vertex.
- Marking a vertex done when it is pushed (the BFS habit) instead of when it is popped: its first, possibly worse, distance gets frozen.
- Processing stale heap entries in full: still correct, but every outdated copy rescans its vertex's edges, which on adversarial inputs can make the run quadratic. Skip any entry whose key exceeds the current distance.
- Running BFS on weighted edges, or Dijkstra's algorithm with negative ones.
- The "at most edges" variant relaxed in place: with 1, 1, 5 and , the answer for is 5, but one in-place round (in that edge order) returns 2, a two-edge path.
- The intermediate-vertex loop of Floyd–Warshall placed anywhere but outermost.
- An undirected edge added in one direction only.
A directed graph has vertices and edges, some of them negative, and no negative cycle. You need the distances from one source within a second. Which algorithm?
- Dijkstra's algorithm with a binary heap
- Bellman–Ford
- Floyd–Warshall
- BFS
Show the answer
B. Bellman–Ford
Bellman–Ford handles negative edges in relaxations, comfortably fast. Floyd–Warshall would also be correct, but it takes steps and computes all pairs, which nobody asked for.
Key takeaways
- All three algorithms only relax edges: . Distances are exact once no edge can be relaxed, and parent pointers form a shortest-path tree.
- Dijkstra's algorithm settles vertices in order of distance and needs non-negative weights; with a binary heap and lazy deletion it runs in .
- Bellman–Ford relaxes every edge times, , handles negative edges, and detects a reachable negative cycle with one more round.
- Floyd–Warshall computes all pairs in by allowing intermediate vertices one at a time; the loop over the intermediate vertex must be outermost.
- BFS (equal weights), 0-1 BFS (weights 0 or 1) and relaxation in topological order (DAGs) beat the general algorithms when they apply.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
In the lazy-deletion version of Dijkstra's algorithm, a popped entry has . Why is it safe to skip it?
- It is an outdated copy: was already settled with the smaller value , and its edges were relaxed then
- It signals a negative cycle through
- It means cannot be reached from the source
- Skipping it is required for correctness: processing it would produce wrong distances
Show the answer
A. It is an outdated copy: was already settled with the smaller value , and its edges were relaxed then
Each improvement of pushed a new entry, so older entries with larger keys stay in the heap. The entry with the final value was popped first and relaxed 's edges. Processing a stale copy would only redo work, which on adversarial inputs can add up.
Why does Bellman–Ford need only rounds when there is no negative cycle?
- Each round settles the vertex closest to the source, as in Dijkstra's algorithm
- Some shortest path to each vertex is simple, so it has at most edges, and round makes every path of at most edges count
- The distances shrink by at least 1 per round, so rounds exhaust them
- Each round relaxes edges
Show the answer
B. Some shortest path to each vertex is simple, so it has at most edges, and round makes every path of at most edges count
After round , is at most the weight of the best path to with at most edges. Without negative cycles, cutting a cycle out of a path never makes it more expensive, so a simple shortest path exists, with at most edges.
After Floyd–Warshall, the diagonal entry is negative. What does that mean?
- An edge leaving has negative weight
- cannot reach itself
- lies on a negative cycle
- An integer overflow occurred at
Show the answer
C. lies on a negative cycle
starts at and only decreases when some path from back to is negative, which is a negative cycle through . Distances between vertices that can reach such a cycle and be reached from it are then meaningless.
An undirected graph has one edge of weight and all other weights positive. You run Bellman–Ford with each edge replaced by two opposite arcs, and it reports a negative cycle. Why?
- Bellman–Ford cannot handle any negative weight
- The edge became the arcs and , a cycle of weight
- Undirected graphs always contain cycles
- The report is a bug: undirected graphs cannot have negative cycles
Show the answer
B. The edge became the arcs and , a cycle of weight
The two arcs of one undirected edge form a 2-cycle whose weight is twice the edge's. With a negative edge, that round trip is a genuine negative cycle in the directed version, so "shortest walks" really are unbounded.
Go deeper
- Dijkstra’s Algorithm in Depth · The proof, heap choices, universal optimality and breaking the sorting barrier.
- Negative Weights: Bellman–Ford, Johnson & Beyond · Negative cycles, reweighting, and the 2022 near-linear-time breakthrough.
- All-Pairs Shortest Paths · Floyd–Warshall, min-plus products and the APSP conjecture.
Further reading
- E. W. Dijkstra, "A note on two problems in connexion with graphs," Numerische Mathematik 1 (1959), 269–271.
- R. Bellman, "On a routing problem," Quarterly of Applied Mathematics 16(1) (1958), 87–90.
- R. W. Floyd, "Algorithm 97: Shortest path," Communications of the ACM 5(6) (1962), 345.
- T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapters 22 and 23.