Sub topic 3
Edge Relaxation: Improving Distance Estimates
This chapter assumes you know basic graph terms, can read adjacency lists stored as Python dicts, and know how breadth-first search works. The earlier chapters defined weighted graphs and the single-source shortest path problem. This chapter covers the one operation behind every shortest-path algorithm in this tutorial: edge relaxation. Dijkstra's algorithm and Bellman-Ford differ only in the order in which they relax edges. If you understand relaxation well, you will find most of what follows easy to reason about.
Tentative Distances
A shortest-path algorithm keeps a tentative distance dist[v] for every vertex v. This number is the length of the best path from the source to v found so far. It is an estimate, and the algorithm only ever improves it.
At the start, nothing is known except the source:
dist[source] = 0, because the empty path costs nothing.dist[v] = ∞for every other vertex, because no path has been found yet.
Next to dist, the algorithm keeps a predecessor prev[v]: the vertex just before v on the best path found so far. It starts as None for everyone. A later chapter uses prev to rebuild whole paths. For now, the rule is that prev[v] changes whenever dist[v] changes.
Write δ(v) for the true shortest-path distance from the source to v. The goal is to drive every dist[v] down until it equals δ(v).
The Relax Operation
To relax an edge (u, v) with weight w, you ask whether the best known path to u, followed by this edge, beats the best known path to v:
- Compute the candidate
dist[u] + w. - If the candidate is strictly smaller than
dist[v], setdist[v]to the candidate and setprev[v] = u. - Otherwise, change nothing.
The name comes from thinking of dist[v] as an upper-bound constraint that gets loosened, or "relaxed", toward its true value. You will see it written as a triangle-inequality check: after relaxing (u, v), the condition dist[v] ≤ dist[u] + w holds.
Relaxation in Python
The code below sets up the initial state and relaxes one edge. It uses math.inf for "no path yet", which means arithmetic on unreached vertices needs no special cases.
import math
def init_single_source(graph, source):
"""graph: dict mapping every node -> list of (neighbor, weight)."""
dist = {v: math.inf for v in graph}
prev = {v: None for v in graph}
dist[source] = 0
return dist, prev
def relax(u, v, w, dist, prev):
"""Try to improve dist[v] using edge (u, v) of weight w.
Returns True if dist[v] decreased."""
candidate = dist[u] + w
if candidate < dist[v]:
dist[v] = candidate
prev[v] = u
return True
return False
graph = {
"A": [("B", 4), ("C", 1)],
"B": [("D", 1)],
"C": [("B", 2), ("D", 5)],
"D": [],
}
dist, prev = init_single_source(graph, "A")
print(relax("A", "B", 4, dist, prev)) # True: inf -> 4
print(relax("A", "B", 4, dist, prev)) # False: 4 is not < 4
print(relax("B", "D", 1, dist, prev)) # True: inf -> 5
print(dist) # {'A': 0, 'B': 4, 'C': inf, 'D': 5}
print(prev) # {'A': None, 'B': 'A', 'C': None, 'D': 'B'}Notice that relaxing the same edge twice in a row does nothing the second time. Relaxation is idempotent when nothing upstream has changed: you only gain something by relaxing (u, v) again after dist[u] has dropped.
Order Matters
Relaxation never produces a wrong answer by itself, but relaxing edges in a careless order can leave estimates too high. Look at the graph above, where the true distances are δ(A)=0, δ(C)=1, δ(B)=3 (via C), and δ(D)=4 (via C and B).
Here we relax every edge once, in a poor order:
def run(order, graph, source):
dist, prev = init_single_source(graph, source)
for u, v, w in order:
relax(u, v, w, dist, prev)
return dist, prev
poor_order = [("A", "B", 4), ("A", "C", 1), ("B", "D", 1),
("C", "B", 2), ("C", "D", 5)]
dist, prev = run(poor_order, graph, "A")
print(dist) # {'A': 0, 'B': 4, ...} -> actually {'A': 0, 'B': 3, 'C': 1, 'D': 5}
# D is too high: B improved *after* B -> D was relaxed. Relax it again:
relax("B", "D", 1, dist, prev)
print(dist["D"]) # 4The second line prints {'A': 0, 'B': 3, 'C': 1, 'D': 5}. Step by step:
| Step | Edge relaxed | Candidate | Update | State after (B, C, D) |
|---|---|---|---|---|
| 1 | A→B (4) | 0 + 4 = 4 | B: ∞ → 4 | 4, ∞, ∞ |
| 2 | A→C (1) | 0 + 1 = 1 | C: ∞ → 1 | 4, 1, ∞ |
| 3 | B→D (1) | 4 + 1 = 5 | D: ∞ → 5 | 4, 1, 5 |
| 4 | C→B (2) | 1 + 2 = 3 | B: 4 → 3 | 3, 1, 5 |
| 5 | C→D (5) | 1 + 5 = 6 | none (6 ≮ 5) | 3, 1, 5 |
At step 3, D took its value from a stale estimate of B. When B improved at step 4, nothing pushed that improvement on to D. One more relaxation of B→D fixes it.
Now relax only the edges of the true shortest path, in path order:
good_order = [("A", "C", 1), ("C", "B", 2), ("B", "D", 1)]
dist, prev = run(good_order, graph, "A")
print(dist) # {'A': 0, 'B': 3, 'C': 1, 'D': 4}Three relaxations are enough to get every distance right. The whole design question for shortest-path algorithms is how to find an order like this without knowing the answer in advance. The next chapter shows how Dijkstra's greedy rule does it.
Properties You Can Rely On
These facts hold for any sequence of relaxations, in any order, after init_single_source. Later chapters, especially the correctness proof, depend on them.
Upper-bound property
At all times, dist[v] ≥ δ(v). Every finite value in dist[v] is the length of a real path from the source: the one you get by following prev pointers back. No real path can be shorter than the shortest one, so relaxation can never undershoot. Once dist[v] = δ(v), it never changes again.
Monotonicity
dist[v] only decreases. The update fires only when the new value is strictly smaller. This is why an algorithm can safely treat a value as final once it knows that value can't drop any further.
No-path property
If v can't be reached from the source, dist[v] stays ∞ forever. Every candidate for v comes from some dist[u] where u has an edge into v. By induction, all of those stay infinite as well.
Path-relaxation property
Let s = v0, v1, ..., vk be a shortest path to vk. If the edges (v0,v1), (v1,v2), ..., (vk-1,vk) are relaxed in that order, then afterwards dist[vk] = δ(vk). This holds even if any other relaxations are mixed in between them. The poor order above shows why: A→C, C→B, and B→D did appear in it, but B→D came before C→B, so the property did not apply.
The proof is short. Subpaths of shortest paths are themselves shortest. After (vi-1, vi) is relaxed, dist[vi] ≤ dist[vi-1] + w = δ(vi-1) + w = δ(vi). Combine that with the upper-bound property and you get equality, and monotonicity keeps it there.
Common Mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Using `<=` instead of `<` | `prev` flips between equal-cost paths. In algorithms that requeue on change, zero-weight cycles can loop forever | Update only on strict improvement |
| Updating `dist[v]` but not `prev[v]` | Distances are right but rebuilt paths are wrong or broken | Always update both together |
| Using `None` or `0` for "unreached" | `TypeError`, or unreached vertices look like the source | Use `math.inf`, or test membership explicitly |
| Relaxing only one direction of an undirected edge | Distances too high on undirected graphs | Store each undirected edge in both adjacency lists |
| Assuming one pass in any order is enough | Some distances stay too high | Choose an order (Dijkstra) or repeat passes (Bellman-Ford) |
Exercises
Exercise
Before relaxing edge (u, v) with weight 3, dist[u] = 7 and dist[v] = 10. What do dist[v] and prev[v] look like afterwards, and what does relax return?
Show answer
The candidate is 7 + 3 = 10, and 10 is not strictly less than 10, so nothing changes. dist[v] stays 10, prev[v] keeps its old value, and relax returns False.
Exercise
In the example graph, list the shortest sequence of relaxations that gives the correct final distance for every vertex (B = 3, C = 1, D = 4). Explain why no shorter sequence exists.
Show answer
A→C, C→B, B→D. Three vertices other than A have finite distances, and each one needs at least one successful relaxation of an edge into it, so at least three relaxations are required. This order relaxes the shortest path A-C-B-D in path order, so the path-relaxation property gives D = 4. B and C are correct along the way.
Exercise
A student says: "After any relaxation, dist[v] might drop below the true shortest distance if we happened to relax a lucky edge." Use the upper-bound property to explain why this is false.
Show answer
Any finite dist[v] equals the cost of a real path from the source to v, namely the one you get by following prev pointers back. A real path can't cost less than the shortest path, so dist[v] ≥ δ(v) always holds. Relaxation can only lower dist[v] toward δ(v), never past it.
Exercise
Run poor_order on the example graph a second time without resetting dist. Which relaxations succeed during the second pass, and what are the final distances?
Show answer
Only B→D succeeds: 3 + 1 = 4 < 5. A→B (0 + 4 = 4, not < 3), A→C, C→B (1 + 2 = 3, not < 3), and C→D (1 + 5 = 6, not < 4) all fail. The final distances are A = 0, B = 3, C = 1, D = 4, which are correct. This is the idea behind Bellman-Ford's repeated passes.