Single-Source Shortest Paths

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.

Race three relaxation orders

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

The Cheapest Next Step Is Not the Cheapest Route

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.

Walk greedy, then walk the shortest path

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 failure, as symptom, measurement and fix

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.

The road

  1. Relaxation: the one move every algorithm repeats.
  2. Why it converges: the triangle inequality and the order of moves.
  3. Bellman-Ford: relax every edge, V − 1 times.
  4. Negative cycles: when no shortest path exists, and how to detect it.
  5. DAG shortest paths: one pass in topological order, and the critical path.
  6. Dijkstra: always relax out of the closest open vertex.
  7. Why Dijkstra is right: the proof, and the negative edge that breaks it.
  8. Difference constraints: solve a system of inequalities with Bellman-Ford.
  9. A*: Dijkstra pulled toward a goal.
  10. The field guide: terms, numbers, code and links.
Edges: A→B weighs 1, A→C weighs 4, B→D weighs 8, C→D weighs 1. What does a greedy walk from A to D cost, and what is δ(A, D)?

Chapter 1

Relaxation: The One Move

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.

Say it aloud

d of v becomes the minimum of d of v, and d of u plus w of u, v.

d[v]
d of v the best distance from s to v found so far. It starts at ∞ and only goes down.
d[u]
d of u the best distance from s to u found so far.
w(u, v)
w of u, v the weight of the edge from u to v.
min
the minimum of the smaller of the two numbers. The arrow ← means "store it in d[v]".
In plain words

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 numbers

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.

Relax one edge at a time

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 failure, as symptom, measurement and fix

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.

d[u] = 3, d[v] = 10 and w(u, v) = 4. What is d[v] after RELAX(u, v)?

Chapter 2

Why Relaxing Converges

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.

Say it aloud

delta of s, v is at most delta of s, u plus w of u, v.

δ(s, v)
delta of s, v the true shortest distance from s to v.
≤
is at most less than or equal to.
δ(s, u)
delta of s, u the true shortest distance from s to u.
w(u, v)
w of u, v the weight of the edge from u to v.
In plain words

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.

With numbers

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.

Find the order that locks v3

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 failure, as symptom, measurement and fix

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.

The shortest path to v is s→a→v. Which sequence of relaxations guarantees d[v] = δ(s, v)?

Chapter 3

Bellman-Ford: Relax Every Edge, Pass After Pass

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.

Say it aloud

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.

dk[v]
d-k of v the shortest distance to v using at most k edges.
dk−1[v]
d-k-minus-one of v the same, with at most k − 1 edges.
min(u,v)∈E
the minimum over every edge u, v try each edge that ends at v and keep the best.
dk−1[u]
d-k-minus-one of u the best way to reach u in at most k − 1 edges.
w(u, v)
w of u, v the weight of the last edge.
In plain words

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.

With numbers

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.

Run Bellman-Ford pass by pass

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 failure, as symptom, measurement and fix

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.

A graph has 6 vertices, 15 edges and no negative cycle. How many relaxations does plain Bellman-Ford make before its final check?

Chapter 4

Negative Cycles: When No Shortest Path Exists

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.

Say it aloud

w of u, v equals minus the natural log of r of u, v.

w(u, v)
w of u, v the weight we give the edge from currency u to currency v.
−ln
minus the natural log of ln turns products into sums; the minus sign turns "more money" into "less weight".
r(u, v)
r of u, v how many units of v one unit of u buys.
In plain words

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 numbers

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.

Tune three rates until the loop pays

Drag the rates. Each edge shows its rate and its weight −ln r. Purple means the loop is a negative cycle.

0.90
0.80
1.50

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 failure, as symptom, measurement and fix

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.

Three trades have rates 2.0, 0.6 and 0.9. Is the loop a negative cycle under w = −ln r?

Chapter 5

Shortest Paths in a DAG: One Pass in the Right Order

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.

Sweep a DAG left to right

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.

The critical path

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).

Say it aloud

L of v equals minus delta-prime of s, v, where w-prime of u, v equals minus w of u, v.

L(v)
L of v the longest path weight from s to v: the earliest time event v can happen.
−
minus flip the sign back at the end.
δ′(s, v)
delta-prime of s, v the shortest distance from s to v using the flipped weights.
w′(u, v)
w-prime of u, v the flipped weight of the edge.
w(u, v)
w of u, v the task's duration.
In plain words

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 numbers

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 failure, as symptom, measurement and fix

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.

Why can the DAG pass relax each edge only once and still be right?

Chapter 6

Dijkstra: Always Settle the Closest Vertex

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.

  1. Put every vertex in a min-priority queue Q keyed by its note d[v].
  2. Take out the vertex u with the smallest note (EXTRACT-MIN) and add it to S. Its note is now final.
  3. Relax every edge out of u. When a note drops, DECREASE-KEY lowers that vertex's key in Q.
  4. Repeat until Q is empty.

Settle one vertex per step

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.

What the queue costs

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.

Say it aloud

T equals V times T-extract, plus E times T-decrease.

T
T the total queue work of one Dijkstra run.
V
V the number of vertices: one EXTRACT-MIN each.
Textract
T-extract the cost of one EXTRACT-MIN.
E
E the number of edges: at most one DECREASE-KEY each.
Tdecrease
T-decrease the cost of one DECREASE-KEY.
In plain words

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 numbers

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.

Price the queue

Drag the size and the density. Bars use a log scale, one step per factor of 10.

1,000
50

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 failure, as symptom, measurement and fix

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.

In the device, why does D close at 8 and not at 9?

Chapter 7

Why Dijkstra Is Right, and What Breaks It

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.

  1. Take a shortest path from s to u. It starts inside S and ends outside, so it crosses out of S. Let y be its first vertex outside S, and x the vertex before y.
  2. x closed earlier with the right note, and Dijkstra relaxed its edges then. By path relaxation, d[y] = δ(s, y).
  3. y comes before u on a shortest path, and the rest of the path has no negative edge. So δ(s, y) ≤ δ(s, u).
  4. u came out of the queue before y, so d[u] ≤ d[y].
  5. Chain them: d[u] ≤ d[y] = δ(s, y) ≤ δ(s, u) ≤ d[u]. Every link is equal, so d[u] = δ(s, u).

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.

Lower one edge until Dijkstra is wrong

Drag the weight of B→A. Small numbers on the vertices give the closing order. Green notes are right, red notes are wrong.

−10

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 failure, as symptom, measurement and fix

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.

Which step of the proof uses "every weight is zero or more"?

Chapter 8

Difference Constraints: Inequalities as a Graph

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.

Say it aloud

x-j minus x-i is at most b, which becomes an edge from v-i to v-j of weight b.

xj
x-j the unknown that the rule limits, such as the start time of event j.
xi
x-i the unknown that the rule measures from.
b
b the limit on the difference. It can be negative.
vi → vj
an edge from v-i to v-j one vertex per unknown. Add a start vertex v0 with a 0-weight edge to every other vertex.
In plain words

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.

With numbers

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:

RuleEdge
x1 − x2 ≤ 0v2→v1, 0
x1 − x5 ≤ −1v5→v1, −1
x2 − x5 ≤ 1v5→v2, 1
x3 − x1 ≤ b (5 in the book)v1→v3, b
x4 − x1 ≤ 4v1→v4, 4
x4 − x3 ≤ −1v3→v4, −1
x5 − x3 ≤ −3v3→v5, −3
x5 − x4 ≤ −3v4→v5, −3

Tighten one rule until no schedule exists

Drag b, the limit on x3 − x1. Each vertex shows its x. Purple edges mark a negative cycle when one appears.

5

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 failure, as symptom, measurement and fix

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.

Which edge stands for the rule x4 − x2 ≤ 7?

Chapter 9

A Star Search: Dijkstra Pulled Toward a Goal

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.

Say it aloud

f of v equals g of v plus h of v.

f(v)
f of v the queue key: the estimated length of the best route through v.
g(v)
g of v the distance from s to v found so far (Dijkstra's d[v]).
h(v)
h of v a guess of the distance from v to the goal. Here: the grid steps left, ignoring walls.
In plain words

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 numbers

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.

Race Dijkstra and A* on a grid

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 failure, as symptom, measurement and fix

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.

On a 4-way grid with moves of cost 1, A* uses h(v) = 3 × (steps left, ignoring walls). What can go wrong?

Chapter 10

The Field Guide

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.

Which algorithm

GraphUseTime
Every weight 1BFSO(V + E)
No cycles (DAG), any weightsTopological sort, then one passO(V + E)
Weights zero or moreDijkstra with a binary heapO((V + E) log V)
Weights zero or more, denseDijkstra with an arrayO(V2)
Negative weights, maybe negative cyclesBellman-FordO(VE)
One target, a good guess of distanceA* with an admissible hDepends on h

The numbers from this page

WhatNumberWhy it matters
Hero graph, relaxationsBF 45, DAG 9, Dijkstra 9Same move, different order
Hero graph with b→c = −4Dijkstra d = 7, t = 9; true 4, 6One negative edge, silent errors
Textbook Bellman-Ford grapht 2, x 4, y 7, z −2Exact after 4 = V − 1 passes
Rates 0.9, 0.8, 1.5cycle weight −0.077Product 1.08 > 1: a negative cycle
DAG sweepshortest 0, 5, 3, 10, 7, 5One pass, negative edges allowed
Project critical path10 days, docs slack 6Longest path by flipping signs
Dijkstra queue, V = 1,000, E = 50,0001,050,000 / 510,000 / 60,000Array / binary / Fibonacci
Difference constraints, b = 5x = (−5, −3, 0, −1, −4)Below b = 5: no solution

Checks after any run

The core, in Python

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

Keep going

The takeaway. A shortest-path algorithm is a schedule for one move. Pick the schedule your graph allows: any order repeated V − 1 times, topological order once, or closest first when no weight is negative.
A graph has cycles and some negative edges but no negative cycle. You need distances from one source. Which algorithm is correct?

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.

Credit and source

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.

CLRS Chapter 24: Single-Source Shortest Paths
The book · Back to Gleams