Learn the pattern · ~15 min
Bellman-Ford
also called edge relaxation rounds, SPFA
Relax every edge, round after round. After round i, every shortest path that uses at most i edges is known.
Reach for it when you read
- +Shortest paths where some edge weights are negative.
- +"Detect a negative cycle", "can the score grow forever?", or return -1 when one exists.
- +A limit on the number of edges: "at most k stops", "within k moves".
- +A system of rules
x[j] − x[i] ≤ c: each rule is an edge, and a negative cycle means no answer.
Not this one when
- ×All weights ≥ 0 and no edge limit: Dijkstra is faster, O(E log V).
- ×Every pair of nodes on a small graph (n ≤ 400): Floyd-Warshall.
- ×Every edge costs the same: plain BFS.
Learn Bellman-Ford
First, what do "relax" and "negative edge" mean?
In a weighted graph, dist[v] is the cheapest cost we know so far to reach v from the source. Relaxing an edge u → v (w) means checking one thing:
if (dist[u] + w < dist[v]) dist[v] = dist[u] + w; // going through u is cheaperIf dist[1] = 1 and there's an edge 1 → 2 (4), then 2 can be reached for 5. If dist[2] was 6, it drops to 5.
A negative edge costs less than 0: a refund, a score that drops. Dijkstra breaks on them: it treats a node as final once popped, and a negative edge found later can still make it cheaper. Bellman-Ford never trusts a node to be final. It relaxes every edge, again and again.
How many times do we relax everything?
Five nodes, edges listed in an unlucky order (the list order is what matters here):
The rule is one line:
One pass = relax every edge once, in list order. Do V − 1 passes.
Here V = 5, so 4 passes. From 0, dist starts as 0 ∞ ∞ ∞ ∞.
| pass | what happens | dist[0..4] after |
|---|---|---|
| 1 | 3→4 and 2→3 start at ∞, skipped. 1→2 too: 1 is still ∞ when it's read. 0→1 sets 1 = 1, 0→2 sets 2 = 6 | 0 1 6 ∞ ∞ |
| 2 | 2→3: 6 − 3 = 3. 1→2: 1 + 4 = 5 beats 6 | 0 1 5 3 ∞ |
| 3 | 3→4: 3 + 2 = 5. 2→3: 5 − 3 = 2 beats 3 | 0 1 5 2 5 |
| 4 | 3→4: 2 + 2 = 4 beats 5 | 0 1 5 2 4 |
The best route to 4 is 0 → 1 → 2 → 3 → 4, cost 1 + 4 − 3 + 2 = 4. It has 4 edges, and it took 4 passes: each pass got one more edge of it right.
The code for it
vector<long long> dist(n, INF); // INF = LLONG_MAX / 4, so INF + w can't overflow
dist[src] = 0;
for (int pass = 1; pass <= n - 1; pass++)
for (auto [u, v, w] : edges)
if (dist[u] != INF && dist[u] + w < dist[v]) // relax
dist[v] = dist[u] + w;
negCycle = false; // pass n: any improvement means a reachable negative cycle
for (auto [u, v, w] : edges)
if (dist[u] != INF && dist[u] + w < dist[v]) negCycle = true;You don't need to memorise this. It's the table: V − 1 passes, each relaxing every edge. Skip edges out of nodes still at ∞, or ∞ + (−3) looks like a real price.
Why exactly V − 1 passes? Two facts:
- Each pass fixes at least one more edge of every best path. Once
dist[u]is right, the next pass reaches the edgeu → vand makesdist[v]right. Pass 1 gets the first edge of the path right, pass 2 the second, and so on. - A best path has at most V − 1 edges. Without a negative cycle, a shortest path never visits a node twice (going around a loop of cost ≥ 0 can't help). V nodes, no repeats, so at most V − 1 edges.
So after V − 1 passes every best path is fixed. The edge order doesn't matter for correctness (the argument never used it), only for how soon things settle: list the edges as 0→1, 0→2, 1→2, 2→3, 3→4 and pass 1 already gives 0 1 5 2 4.
That's also why one extra pass catches a negative cycle. With 0→1 (1), 1→2 (2), 2→1 (−4), every lap of 1 → 2 → 1 saves 2, so dist never stops falling: after 2 passes it's 0 −3 1, and pass 3 still improves. negCycle = true.
Fine, but how does this help us?
The classic problem: Cheapest Flights Within K Stops. Flights u → v cost a price. Find the cheapest price from src to dst using at most k stops, or -1.
k stops means k + 1 flights, so at most 2 flights. Solve it by hand, listing every route to 3:
| route | flights | stops | allowed? | price |
|---|---|---|---|---|
| 0→1→2→3 | 3 | 2 | no, one stop too many | 300 |
| 0→1→3 | 2 | 1 | yes | 700 |
| 0→2→3 | 2 | 1 | yes | 600 |
The cheapest allowed route is 0 → 2 → 3, so the answer is 600, not 300.
The brute force
Try every route of at most k + 1 flights with a DFS, and keep the cheapest one that reaches dst.
int cheapestSlow(int n, vector<vector<int>>& flights, int src, int dst, int k) {
vector<vector<pair<int, int>>> adj(n);
for (auto& f : flights) adj[f[0]].push_back({f[1], f[2]});
long long best = INF;
function<void(int, int, long long)> go = [&](int city, int flightsLeft, long long cost) {
if (city == dst) { best = min(best, cost); return; }
if (flightsLeft == 0) return;
for (auto [next, price] : adj[city])
go(next, flightsLeft - 1, cost + price); // try every next flight
};
go(src, k + 1, 0); // k stops = k + 1 flights
return best == INF ? -1 : (int)best;
}It's correct, but the routes multiply: with 10 flights out of each city, k + 1 flights is 10^(k+1) routes. LeetCode allows 100 cities and k up to 99; with k = 9 that's 10¹⁰ routes, about 20 seconds at -O2. Time limit exceeded.
The one thought that fixes it
Bellman-Ford already counts edges: pass r fixes the r-th edge of a path. So you'd hope that after pass r, dist[v] is the cheapest price using at most r flights, and k + 1 passes give the answer.
But stop inside pass 1 and watch the plain loop, in list order:
0→1:dist[1] = 100.1→2: reads the 100 that was set a moment ago, in this same pass:dist[2] = 200.2→3: reads that 200:dist[3] = 300.
One pass, three flights. Updating in place lets a pass run ahead along the list. For plain shortest paths that only settles things sooner; here the flight count is the whole point.
The fix: at the start of each pass, copy dist into prev, and read only from prev. Then a price set in pass r can't be extended until pass r + 1, and pass r really means "one more flight".
int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int k) {
vector<long long> dist(n, INF);
dist[src] = 0;
for (int pass = 1; pass <= k + 1; pass++) { // k stops = k + 1 flights
vector<long long> prev = dist; // read only last pass's prices
for (auto& f : flights) {
int u = f[0], v = f[1], w = f[2];
if (prev[u] != INF && prev[u] + w < dist[v])
dist[v] = prev[u] + w;
}
}
return dist[dst] == INF ? -1 : (int)dist[dst];
}Dry run
Same flights, k = 1, so 2 passes.
| pass | reads (prev) | what happens | dist after |
|---|---|---|---|
| 1 | 0 ∞ ∞ ∞ | only 0's flights can be used: 1 = 100, 2 = 500 | 0 100 500 ∞ |
| 2 | 0 100 500 ∞ | 1→2: 100 + 100 = 200 beats 500. 2→3: prev[2] is 500, so 3 = 600. 1→3: 700, no better | 0 100 200 600 |
600, the same answer as the brute force. Without the copy, it returns 300 here, and 300 even for k = 0, where the right answer is -1 (there's no direct flight).
Why it's O(V · E)
Count what happens to each edge: it's relaxed once per pass. Plain Bellman-Ford makes V − 1 passes, so O(V · E) time and O(V) space. With the k-stops limit it's k + 1 passes: O(k · E), plus O(V) for the copy each pass.
From 10^(k+1) routes down to (k + 1) · E relaxations, by letting each pass add exactly one more flight.
Done early? Stop when a pass changes nothing
If a whole pass changes nothing, no later pass can either, since it would read exactly the same numbers.
bool changed = false;
for (auto [u, v, w] : edges)
if (dist[u] != INF && dist[u] + w < dist[v])
dist[v] = dist[u] + w, changed = true;
if (!changed) break; // settled early: nothing left to fixOn the edge order 0→1, 0→2, 1→2, 2→3, 3→4, this stops after pass 2 instead of running 4.
Remember this
- Negative weights, or "detect a negative cycle" → Bellman-Ford. All weights ≥ 0 → Dijkstra is faster.
- V − 1 passes, because a best path has at most V − 1 edges and each pass fixes one more. Edge order is free.
- A limit on the number of edges (k stops) → k + 1 passes, each reading a copy of the last pass.
- Skip edges out of
∞, and useINF = LLONG_MAX / 4so adding a weight can't overflow.
Practise it on Network Delay Time (plain shortest path), then Cheapest Flights Within K Stops (the copy), Cycle Finding (find and print a negative cycle) and High Score (an infinite score only counts if it can reach the end).
Below, watch Cheapest Flights Within K Stops run line by line.
Watch it work, line by line
Cheapest Flights Within K Stops ↗, n = 4, flights 0→1:100 1→2:100 2→0:100 1→3:600 2→3:200, src 0, dst 3, k = 1 → 700. Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.
When to use it, and when not
Ask yourself
Are there negative weights, a limit on the number of edges, or a question about cycles that keep making things cheaper?
Reach for it when
- +negative edge weights
- +detect a negative (or positive, for longest path) cycle
- +at most K edges / stops
- +V*E up to ~1e7-1e8
It fails when
- ×Large graph, all weights non-negativeuse Dijkstra, O(E log V)
- ×All-pairs distances on small Vuse Floyd-Warshall
Looks like it, isn't (and the other way round)
- Cheapest Flights Within K Stops looks like Dijkstra (Weighted Shortest Path), needs this pattern
The stop limit invalidates per-vertex optimality; k+1 Bellman-Ford rounds (or Dijkstra over (city, stops)).
- Path with Maximum Probability looks like Bellman-Ford, needs Dijkstra (Weighted Shortest Path)
Multiplying probabilities <= 1 never increases a path's value, so Dijkstra with a max-heap is valid.
Recall card
Answer each one out loud before you open it. Come back in three days and try again without reading the page.
1What does round i of Bellman-Ford guarantee?Reveal
Every shortest path that uses at most i edges has been found.
2Why copy
distinto a snapshot at the start of each round in Cheapest Flights?RevealSo a route grows by at most one flight per round. Without it, one round can chain several new flights and break the stop limit.
3How do you detect a negative cycle?Reveal
Run one more round after n − 1. If any distance still drops, a negative cycle exists.
Practice ladder
Finished Bellman-Ford? Mark it done and Lessgo moves you to the next step.