Every algorithm in this chapter repeats one move: relax an edge. Bellman-Ford, the DAG pass and Dijkstra differ only in the order of the moves. On one 9-edge graph that is 45, 9 and 9 relaxations, and one negative edge breaks only Dijkstra.
Learn CLRS Chapter 24: relaxation, Bellman-Ford and negative cycles, shortest paths in a DAG, Dijkstra and its proof, difference constraints and A*.
Pick an algorithm and press Play. Then switch on the negative edge and play Dijkstra again. Watch which distances turn red. Then we build each algorithm, piece by piece, from the one move they share.
You need a little Python, graphs and BFS and the idea of a priority queue. We build the rest from zero.
Re-taught from Chapter 24, Single-Source Shortest Paths, in the third edition of Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms (CLRS). In the fourth edition it is Chapter 22. The toys and traces here are our own, and a script checked every number.
The graph is illustrative and has no cycles, so all three algorithms may run on it. Each relaxation is one call of RELAX (Chapter 1). Bellman-Ford here is the plain textbook version: V − 1 = 5 full passes over all 9 edges.
Chapter 0
See why a greedy walk fails, and name what a shortest path is
You stand at s and want to reach t. Each road has a cost in minutes. The obvious plan is to take the cheapest road out of wherever you stand. Try it on the graph below.
Grey is the greedy walk. Blue is the shortest path. Pick one and watch it draw.
Same illustrative graph as the hero, with every weight positive.
Greedy pays 2, 3, 2, 3 and 2, a total of 12. The route s→c→d→t starts with a dearer road of 4 and costs 9. A cheap first step can lead you into a long detour, so you must compare whole routes.
A weighted directed graph is a set of vertices joined by one-way edges, each with a number called its weight. The weight of a path is the sum of its edge weights. The shortest-path weight δ(s, v), read "delta of s, v", is the smallest weight of any path from s to v. It is ∞ if no path exists.
The single-source problem asks for δ(s, v) for every v at once, plus one path that achieves it. Weights can mean minutes, dollars or risk. Some can be negative, such as a refund on a road.
The symptom is a route that looks cheap step by step and costs more in total. To measure it, compare its total with the best total over all routes. The fix is the subject of this lesson: keep a best-known distance for each vertex and improve it until no edge can improve it further.
Chapter 1
Keep a best-known distance on each vertex and lower it when a shorter route appears
Put a sticky note on every vertex. The note holds the shortest distance from s found so far. At the start you know almost nothing: the note on s says 0 and every other note says ∞. This start is INITIALIZE-SINGLE-SOURCE.
Now look at one edge from u to v. Call the note on v d[v], the note on u d[u], and the edge weight w(u, v). If going to u and then along the edge beats the note on v, write the smaller number on v. Also record u as v's predecessor π[v], read "pi of v": the vertex you came from.
d of v becomes the minimum of d of v, and d of u plus w of u, v.
Add w(u, v) to d[u]. If the sum is smaller than d[v], replace d[v] with the sum and set π[v] to u. If not, change nothing.
With the graph below: d[A] = 5, d[B] = 10, w(A, B) = 3. The sum is 5 + 3 = 8, and 8 < 10, so d[B] becomes 8 and π[B] becomes A.
Press Step. Orange is the edge under test. Blue edges are the predecessors. Then try the reversed order.
Edges: s→A 5, s→B 10, A→B 3, A→C 2, B→C 1. Illustrative weights.
In the first order, step 3 is the one that matters. The direct road s→B costs 10, but s→A→B costs 8. So B's note drops, and its predecessor moves from s to A. Step 5 changes nothing, because 8 + 1 = 9 does not beat 7.
In the reversed order, one pass leaves B at 10 and C at ∞. RELAX tested the edges into C while A and B still said ∞. The order of the moves decides how many moves you need. Each algorithm in this lesson is a different order.
The predecessors form the shortest-path tree: follow π back from any vertex to s and you read off its route. Here C gives C, A, s, so the route is s→A→C.
The symptom is a distance that is right while the route is wrong. To measure it, walk π back from v and add the weights; the sum must equal d[v]. The usual cause is updating d[v] and forgetting π[v]. The fix is to set both in the same branch.
Chapter 2
Use the triangle inequality to show a note never undershoots, and find the order that locks it
Relaxation is safe and it is enough. Safe means a note never goes below the true distance. Enough means the right order of moves makes every note exact. Two facts give both.
The first fact is about true distances. Take any edge from u to v. Call the true distance to u δ(s, u) and the true distance to v δ(s, v). One way to reach v is the best route to u, then this edge. So the best route to v can be no longer.
delta of s, v is at most delta of s, u plus w of u, v.
The best route to u, plus the edge to v, is one route to v. So δ(s, v) is no bigger than that sum. This is the triangle inequality.
In the chain below, δ(s, v2) = 5 and w(v2, v3) = 1, so δ(s, v3) ≤ 6. The direct edge gives δ(s, v3) ≤ 0 + 9. The true value is 6, so the first bound is tight.
From it comes the upper-bound property: every note d[v] stays at or above δ(s, v). A note starts at ∞. Each relaxation writes d[u] + w(u, v). That sum is at least δ(s, u) + w(u, v), and so at least δ(s, v).
The second fact is about order. Let the shortest path to v be s, v1, v2, and so on to v. If you relax its edges in path order, perhaps with other moves mixed in between, then d[v] ends exact. This is the path-relaxation property. Each relaxation hands an exact note one step down the path.
Press the edge buttons in any order. Blue marks the part of the shortest path already relaxed in order.
Edges: s→v1 2, v1→v2 3, v2→v3 1, s→v3 9. The shortest path to v3 is the chain, weight 6. Illustrative weights.
Press v2→v3 first and nothing happens, because v2 still says ∞. Press s→v3 and v3 drops to 9, a true route but not the best. Only after s→v1, v1→v2, v2→v3 appear in that order does v3 reach 6. Extra presses between them do no harm.
The symptom is a note below the true distance, which relaxation alone can never cause. Measure it by checking d[v] against a brute-force answer on a small graph. If it happens, the cause is a bug outside RELAX, such as a note set by hand. The fix is to change notes only through RELAX.
Chapter 3
Make no guess about order, and repeat a full pass until the passes cover every shortest path
You do not know the shortest paths, so you cannot relax their edges in order. Bellman-Ford's answer: relax every edge in one pass, then do it again. Each pass is sure to extend every shortest path by at least one edge.
How many passes? A shortest path never repeats a vertex when no negative cycle exists. With V vertices it has at most V − 1 edges. So V − 1 passes cover every shortest path in order, and the path-relaxation property makes every note exact.
Write this as a recurrence. Call dk[v] the weight of the shortest path to v that uses at most k edges. A path of at most k edges either uses at most k − 1, or it ends with some edge from u to v.
d-k of v equals the minimum of d-k-minus-one of v, and the minimum over every edge u, v of d-k-minus-one of u plus w of u, v.
For pass k, start from last pass's note on v. For each edge into v, add w(u, v) to last pass's note on u. Keep the smallest. Pass k is one round of relaxing every edge.
On the graph below: d2[t] = 6, d2[x] = 4 and w(x, t) = −2. So d3[t] = min(6, 4 − 2) = 2. The best route to t uses 3 edges: s→y→x→t.
Press Edge to relax one edge, or Pass for all ten. Purple weights are negative. The table fills one row per pass.
The graph and edge order are those of the textbook's Bellman-Ford example (Figure 24.4 in the third edition): (t,x), (t,y), (t,z), (x,t), (y,x), (y,z), (z,x), (z,s), (s,t), (s,y). Our script reproduces its final distances 2, 4, 7 and −2.
After pass 4 the notes read t = 2, x = 4, y = 7 and z = −2. Bellman-Ford then makes one more scan of all edges. If any edge can still relax, it reports a negative cycle (Chapter 4). Here none can, so it returns TRUE.
The cost is plain: V − 1 passes of E relaxations, so O(VE). For V = 5 and E = 10 that is 40 relaxations plus a scan of 10. You may stop early after a pass that changes nothing, but the worst case stays O(VE).
The symptom is wrong distances on a long chain when the code stops at V − 2 passes. Measure it on a chain of V vertices with the edges listed backwards: each pass moves the exact note one vertex. The fix is the full V − 1 passes.
Chapter 4
Detect a loop that pays you to go round it, and turn exchange rates into one
A negative-weight cycle is a loop whose edge weights sum below zero. Each lap lowers the total, so a route through it has no minimum. For any v reachable from such a loop, the textbook sets δ(s, v) = −∞.
Bellman-Ford detects this. Without a negative cycle, V − 1 passes make every note exact, and then no edge can relax. So after the passes it scans every edge once more. If d[v] > d[u] + w(u, v) for any edge, a reachable negative cycle exists, and it returns FALSE.
Here is a place where such a loop means money. Three currencies trade with each other. Call the rate for changing one unit of currency u into currency v r(u, v). A round trip multiplies your money by the product of its rates. Shortest paths add, so take logarithms: the log of a product is the sum of the logs.
w of u, v equals minus the natural log of r of u, v.
Give each trade the weight −ln r(u, v). A loop of trades has weight below zero exactly when the product of its rates r is above 1. Then Bellman-Ford's final scan finds the loop, which is free money.
With made-up rates 0.9, 0.8 and 1.5: the weights are 0.105, 0.223 and −0.405. They sum to −0.077, below zero. The product is 0.9 × 0.8 × 1.5 = 1.08: one dollar comes back as 1.08.
Drag the rates. Each edge shows its rate and its weight −ln r. Purple means the loop is a negative cycle.
Made-up rates, with one trade direction each so the toy stays small. The verdict comes from Bellman-Ford run from USD: 2 passes, then the extra scan.
Move GBP→USD down to 1.38 and the product falls to 0.994. The loop weight turns positive, and the scan finds nothing. Real markets add fees and move fast, so treat this as the shape of the idea, not a trading plan.
The symptom is a false alarm: a cycle weight like −0.0000001 that comes from rounding, not from the market. To measure it, print the cycle and its product of rates. The fix is a tolerance: count an edge as relaxable only if it improves by more than a small epsilon.
Chapter 5
Sort the vertices so every edge points forward, relax each edge once, and find a project's critical path
A DAG is a directed acyclic graph: a directed graph with no cycles. Its vertices have a topological order, a line-up in which every edge points from left to right. Depth-first search finds one in O(V + E).
Visit the vertices in that order and relax the edges out of each. Any path is a left-to-right walk in the line-up, so its edges get relaxed in path order. By the path-relaxation property, one pass makes every note exact. The pass relaxes each edge once, so the cost is O(V + E). Negative weights are fine, because a DAG has no cycle to go negative.
Press Step to process the next vertex. Teal vertices hold final notes. Switch to longest paths and sweep again.
Edges: 0→1 5, 0→2 3, 1→2 2, 1→3 6, 2→3 7, 2→4 4, 2→5 2, 3→4 −1, 3→5 1, 4→5 −2. Illustrative weights.
The shortest sweep ends with d = 0, 5, 3, 10, 7, 5. At vertex 2, the edge 2→3 lowers vertex 3 from 11 to 10. The two routes to vertex 5, 0→2→5 and 0→2→4→5, tie at 5.
Now let vertices be project events and edge weights be task durations in days. A task can start only when all tasks before it finish. The project's length is the longest path, the critical path. Longest paths are hard in general graphs, but easy in a DAG. Flip each weight's sign: call the flipped weight w′(u, v) and the shortest distance under it δ′(s, v).
L of v equals minus delta-prime of s, v, where w-prime of u, v equals minus w of u, v.
Replace every w(u, v) with w′(u, v) = −w(u, v). Run the DAG pass to get δ′(s, v). Flip the sign again to get L(v). The smallest negative total is the largest positive one.
With made-up tasks: Start→Design 3 days, Design→Code 5, Code→Test 2, and Start→Docs 4, Docs→Test 0. Flipped, δ′(Start, Test) = −3 − 5 − 2 = −10, so L(Test) = 10 days. The docs branch takes 4 days, so it has 6 days of slack.
In the device's longest mode the sweep ends with 0, 5, 7, 14, 13, 15. Flipping signs works only because a DAG has no cycles. In a general graph, flipped positive cycles become negative cycles.
The symptom is a vertex whose note drops after the pass leaves it. Measure it by asserting that no later step lowers a visited vertex's note. The cause is an order that is not topological, often from a cycle. The fix is to check the sort found all V vertices.
Chapter 6
Use a priority queue to pick the next vertex, and pay for it in heap operations
Drop a stone in a pond. The ripple reaches near points before far ones. Dijkstra's algorithm grows a set S of closed vertices the same way, nearest first. It needs one rule: every edge weight is zero or more.
Press Step. Yellow vertices wait in the queue, shown sorted below. Teal vertices are closed. Blue edges are the tree.
Edges: A→B 2, A→C 4, B→C 1, B→D 7, C→E 3, D→F 1, E→D 2, E→F 5. Illustrative weights.
The closing order is A 0, B 2, C 3, E 6, D 8, F 9. Two notes drop on the way. B lowers C from 4 to 3. E lowers D from 9 to 8, and then D lowers F from 11 to 9. The route to F is A→B→C→E→D→F: 2 + 1 + 3 + 2 + 1 = 9.
Dijkstra calls EXTRACT-MIN once per vertex and DECREASE-KEY at most once per edge. Call the cost of one EXTRACT-MIN Textract and the cost of one DECREASE-KEY Tdecrease.
T equals V times T-extract, plus E times T-decrease.
Count V extractions and up to E key changes. Multiply each count by its price in the queue you chose, Textract and Tdecrease. Add the two.
With V = 1,000, E = 50,000 and log2 1,000 about 10. Array: 1,000 × 1,000 + 50,000 × 1 = 1,050,000. Binary heap: 1,000 × 10 + 50,000 × 10 = 510,000. Fibonacci heap: 1,000 × 10 + 50,000 × 1 = 60,000.
Drag the size and the density. Bars use a log scale, one step per factor of 10.
Operation counts from the formula above, with unit constants: array V·V + E, binary heap (V + E) log2 V, Fibonacci heap V log2 V + E (amortized). Real run times also depend on constants and memory.
A dense graph favours the plain array, and a sparse one favours the binary heap. Prim's algorithm for minimum spanning trees has the same loop. Its key is the lightest edge into the tree, not the distance from s.
The symptom is a slow run with correct answers. Python's heapq has no DECREASE-KEY, so code pushes a new entry instead, and stale entries pile up. Measure the pops: they should stay near E. The fix is to skip a popped vertex that is already closed.
Chapter 7
Follow the proof to the one step that needs non-negative weights, then break that step
The claim: when Dijkstra takes u out of the queue, d[u] = δ(s, u). The proof looks at the first vertex u that would close with a wrong note.
d[u] ≤ d[y] = δ(s, y) ≤ δ(s, u) ≤ d[u]
Step 3 is the one that needs weights of zero or more. A negative edge after y could make u closer than y. Then Dijkstra closes u too early, and the vertices it reaches from u inherit the error.
Drag the weight of B→A. Small numbers on the vertices give the closing order. Green notes are right, red notes are wrong.
Edges: s→A 1, s→B 5, B→A as set, A→C 1. Dijkstra here is the textbook version: RELAX may still lower the note of a closed vertex, but that vertex's edges are never relaxed again.
With w(B, A) = −10, Dijkstra closes s, A at 1, C at 2, then B at 5. Relaxing B→A lowers A's note to −5, which is right. But C closed at 2 and never hears about it. The true distance to C is −4. The error starts as soon as 5 + w(B, A) < 1, that is at w(B, A) = −5.
Bellman-Ford and the DAG pass have no such problem. For many sources on a graph with negative edges, Johnson's algorithm reweights the edges to be non-negative first (see all-pairs shortest paths).
The symptom is silent: no error, no crash, a few wrong distances. Measure it by checking the triangle inequality d[v] ≤ d[u] + w(u, v) on every edge after the run. Any edge that fails means a wrong answer. The fix is Bellman-Ford, or a guard that rejects negative weights.
Chapter 8
Turn rules like "x2 is at most 3 after x1" into edges, and let Bellman-Ford solve or refuse
You schedule five events. Each rule says how far one start time may sit after another: "event 3 starts at most 5 hours after event 1". Write each start time as a number xi. Each rule becomes a difference constraint, an inequality on the difference of two unknowns.
Call the two unknowns xj and xi and the limit b. Compare with the triangle inequality from Chapter 2: δ(s, v) − δ(s, u) ≤ w(u, v). It has the same shape.
x-j minus x-i is at most b, which becomes an edge from v-i to v-j of weight b.
Make one vertex per unknown and one edge vi → vj of weight b per rule. Run Bellman-Ford from v0. Set each xj to δ(v0, vj). The triangle inequality makes every rule hold. A negative cycle means no answer exists.
The rule x5 − x3 ≤ −3 is the edge v3 → v5 of weight −3. Bellman-Ford gives x3 = 0 and x5 = −4. Check: −4 − 0 = −4, which is at most −3.
The device uses the textbook's example system of eight rules on five unknowns:
| Rule | Edge |
|---|---|
| x1 − x2 ≤ 0 | v2→v1, 0 |
| x1 − x5 ≤ −1 | v5→v1, −1 |
| x2 − x5 ≤ 1 | v5→v2, 1 |
| x3 − x1 ≤ b (5 in the book) | v1→v3, b |
| x4 − x1 ≤ 4 | v1→v4, 4 |
| x4 − x3 ≤ −1 | v3→v4, −1 |
| x5 − x3 ≤ −3 | v3→v5, −3 |
| x5 − x4 ≤ −3 | v4→v5, −3 |
Drag b, the limit on x3 − x1. Each vertex shows its x. Purple edges mark a negative cycle when one appears.
At b = 5 our Bellman-Ford gives x = (−5, −3, 0, −1, −4), the textbook's solution. Adding the same number to every x gives another solution.
Drag b down to 4. The loop v1→v3→v4→v5→v1 weighs 4 − 1 − 3 − 1 = −1. Add its four rules and the left sides cancel to 0 ≤ −1, which is false. So the cycle is a proof that no schedule exists.
The symptom is a solution that breaks a rule. Measure it by checking every xj − xi ≤ b after the run. The usual cause is an edge drawn the wrong way round. The fix: the rule xj − xi ≤ b points from i to j.
Chapter 9
Add a guess of the distance left, and explore far fewer vertices when you want one target
Dijkstra spreads out in every direction, behind you as much as ahead. When you want one target, most of that work is waste. A* (Hart, Nilsson and Raphael, 1968) orders the queue by distance so far plus a guess of the distance left. A* is not in CLRS; it is the most common next step after this chapter.
Call the distance from s to v found so far g(v), the same number as d[v]. Call the guess of the distance from v to the goal h(v), the heuristic.
f of v equals g of v plus h of v.
For each open vertex, add the guess h(v) to the known g(v). Close the vertex with the smallest f(v), as Dijkstra closes the smallest d. With h(v) = 0 for all v, A* is Dijkstra.
With made-up cells: cell P ahead of the start has g = 3 and h = 7, so f = 10. Cell Q behind the start has g = 1 and h = 11, so f = 12. A* closes P first. Dijkstra would close Q first, because 1 < 3.
A* returns a shortest path if h never overestimates the true distance left. Such an h is admissible. If also h(u) ≤ w(u, v) + h(v) on every edge, h is consistent, and A* never needs to reopen a closed vertex. On a grid with 4-way moves of cost 1, the step count |Δx| + |Δy| ignoring walls is both.
Pick an algorithm and press Run. Shaded cells are the ones it closed. Tap cells to add or remove walls.
An illustrative grid with 4-way moves of cost 1. The heuristic is the step count to the goal ignoring walls. Ties in f go to the cell with the larger g.
Both searches find a path of the same length. A* closes a narrow band toward the goal, while Dijkstra closes a wide diamond around the start. A wall between them makes h less accurate, so A* explores more, but it never returns a longer path.
The symptom is a path longer than Dijkstra's. Measure it by comparing h(v) with the true distance left on a few cells. Straight-line distance times 2 is a typical overestimate. The fix is an h that never overestimates, such as the step count for 4-way moves.
Chapter 10
Keep the choices, the numbers, the checks and the code in one place
Every algorithm here starts each note at ∞, the source at 0, and lowers notes only by relaxing edges. Bellman-Ford relaxes all edges V − 1 times and detects negative cycles. The DAG pass relaxes in topological order once. Dijkstra relaxes out of the closest open vertex and needs weights of zero or more.
| Graph | Use | Time |
|---|---|---|
| Every weight 1 | BFS | O(V + E) |
| No cycles (DAG), any weights | Topological sort, then one pass | O(V + E) |
| Weights zero or more | Dijkstra with a binary heap | O((V + E) log V) |
| Weights zero or more, dense | Dijkstra with an array | O(V2) |
| Negative weights, maybe negative cycles | Bellman-Ford | O(VE) |
| One target, a good guess of distance | A* with an admissible h | Depends on h |
| What | Number | Why it matters |
|---|---|---|
| Hero graph, relaxations | BF 45, DAG 9, Dijkstra 9 | Same move, different order |
| Hero graph with b→c = −4 | Dijkstra d = 7, t = 9; true 4, 6 | One negative edge, silent errors |
| Textbook Bellman-Ford graph | t 2, x 4, y 7, z −2 | Exact after 4 = V − 1 passes |
| Rates 0.9, 0.8, 1.5 | cycle weight −0.077 | Product 1.08 > 1: a negative cycle |
| DAG sweep | shortest 0, 5, 3, 10, 7, 5 | One pass, negative edges allowed |
| Project critical path | 10 days, docs slack 6 | Longest path by flipping signs |
| Dijkstra queue, V = 1,000, E = 50,000 | 1,050,000 / 510,000 / 60,000 | Array / binary / Fibonacci |
| Difference constraints, b = 5 | x = (−5, −3, 0, −1, −4) | Below b = 5: no solution |
pythonimport heapq INF = float('inf') def bellman_ford(V, edges, s): # edges: list of (u, v, w) d = {v: INF for v in V}; pi = {v: None for v in V}; d[s] = 0 for _ in range(len(V) - 1): for u, v, w in edges: if d[u] + w < d[v]: d[v], pi[v] = d[u] + w, u ok = all(d[u] + w >= d[v] for u, v, w in edges) # False: negative cycle return d, pi, ok def dag_shortest(order, adj, s): # order: a topological order d = {v: INF for v in order}; d[s] = 0 for u in order: for v, w in adj.get(u, []): if d[u] + w < d[v]: d[v] = d[u] + w return d def dijkstra(adj, s): # adj[u] = [(v, w)], every w >= 0 d, pi, done = {s: 0}, {s: None}, set() pq = [(0, s)] while pq: du, u = heapq.heappop(pq) if u in done: continue # a stale entry: skip it done.add(u) for v, w in adj.get(u, []): if du + w < d.get(v, INF): d[v], pi[v] = du + w, u heapq.heappush(pq, (d[v], v)) # push instead of DECREASE-KEY return d, pi
Now press Present or Teach. Explain from memory RELAX, why Bellman-Ford needs V − 1 passes, why the DAG pass needs one, and where Dijkstra's proof uses non-negative weights. Then go back to the hero, switch on the negative edge, and say why d and t turn red while c stays green.
This lesson re-teaches Chapter 24, Single-Source Shortest Paths, in the third edition of Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms (Chapter 22 in the fourth edition). Dijkstra's algorithm is from Edsger Dijkstra, "A note on two problems in connexion with graphs", 1959. A* is from Hart, Nilsson and Raphael, 1968. The toys, graphs and traces here are our own unless the text names the book's example.