Sub topic 3
Edge Relaxation: The Core Operation
This chapter assumes you can read Python and know what a weighted directed edge (u, v, w) is. You should also understand the single-source shortest path problem from the previous chapter. Every algorithm in this tutorial is built from one small operation called edge relaxation. Bellman-Ford, Floyd-Warshall, Dijkstra, and Johnson's algorithm differ mainly in which edges they relax and in what order. To understand those algorithms and debug them, you first need to understand relaxation itself.
What Relaxation Does
Each vertex v keeps a distance estimate dist[v]. This is the length of the best path from the source to v found so far. The algorithm starts with dist[source] = 0 and every other estimate set to infinity, which means "no path known yet."
To relax an edge (u, v, w), you ask one question: does going to u first and then taking this edge beat the best route to v we know about? If it does, you lower dist[v] and record u as the predecessor of v.
import math
def relax(dist, pred, u, v, w):
"""Try to improve dist[v] using edge (u, v) of weight w.
Returns True if the estimate changed."""
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
pred[v] = u
return True
return False
dist = [0, math.inf, math.inf]
pred = [None, None, None]
print(relax(dist, pred, 0, 1, 7), dist, pred) # True [0, 7, inf] [None, 0, None]
print(relax(dist, pred, 0, 2, 2), dist, pred) # True [0, 7, 2] [None, 0, 0]
print(relax(dist, pred, 2, 1, 3), dist, pred) # True [0, 5, 2] [None, 2, 0]
print(relax(dist, pred, 1, 2, 1), dist, pred) # False [0, 5, 2] [None, 2, 0]The name comes from the inequality being enforced. A correct shortest-path solution must satisfy the triangle inequality for every edge: dist[v] <= dist[u] + w. An edge that violates it is "tense," and relaxing it removes the tension by making the inequality hold again.
The Properties That Make Relaxation Safe
Relaxation is useful because it has guarantees that hold no matter how you schedule it. Write δ(s, v) for the true shortest distance from source s to v.
Upper-bound property
At every moment, dist[v] >= δ(s, v). Each finite value of dist[v] is the length of a real walk from s to v, built from earlier relaxations. No real walk can be shorter than the shortest one. So relaxation never undershoots, and an estimate that reaches δ(s, v) never changes again, because the strict < test can never pass after that.
Monotonicity
Estimates only go down. Relaxation either lowers dist[v] or does nothing. Because of this, it is always safe to relax an edge "too often." Extra relaxations waste time but never break correctness.
Path-relaxation property
Let s = v0 → v1 → ... → vk be a shortest path. Suppose the edges (v0, v1), (v1, v2), ..., (vk-1, vk) are relaxed in that order. Then dist[vk] = δ(s, vk) afterward. This holds even if any number of other relaxations happen in between. Each step passes a correct value one hop further along the path, and the upper-bound property ensures nothing can later spoil a correct value.
This property is the key to the whole tutorial. An algorithm is correct if its relaxation schedule is guaranteed to contain every shortest path's edges as an in-order subsequence. Dijkstra gets that guarantee by processing vertices in order of distance, which needs non-negative weights. Bellman-Ford gets it by brute force, and a later chapter shows why V-1 full passes are enough.
Order Matters
One pass over the edges can solve a graph completely or barely start it, depending on the order. The same five edges are relaxed once below, first in a good order and then in reverse.
import math
def relax(dist, pred, u, v, w):
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
pred[v] = u
return True
return False
def one_pass(n, edges, source):
dist = [math.inf] * n
pred = [None] * n
dist[source] = 0
for u, v, w in edges:
relax(dist, pred, u, v, w)
return dist
edges = [(0, 1, 4), (0, 2, 5), (1, 2, -3), (2, 3, 4), (1, 3, 6)]
print(one_pass(4, edges, 0)) # [0, 4, 1, 5] already final
print(one_pass(4, edges[::-1], 0)) # [0, 4, 5, inf] far from finalIn the forward order, the shortest path 0 → 1 → 2 → 3 has its edges relaxed in sequence, so the path-relaxation property finishes the job in one pass. In reverse order, edges out of vertices 1 and 2 are tried before those vertices have finite estimates, so they do nothing. Bellman-Ford does not know a good order ahead of time, so it repeats passes until the order no longer matters.
Relaxing Through a Vertex
Floyd-Warshall uses a two-hop version of the same idea. Instead of asking "does edge (u, v) improve v?", it asks whether going through vertex k improves the route from i to j:
if dist[i][k] + dist[k][j] < dist[i][j]:
dist[i][j] = dist[i][k] + dist[k][j]Here dist[i][k] plays the role of dist[u] and dist[k][j] plays the role of the edge weight. The upper-bound and monotonicity properties still hold. The only change is that the "edge" is now a best-known path. A later chapter turns this into a dynamic programming recurrence.
Common Errors
| Mistake | Symptom | Fix |
|---|---|---|
| Using `<=` instead of `<` | Predecessors keep switching between equal-cost paths; early-exit checks never see "no change" on graphs with zero-weight cycles | Use strict `<` |
| Updating `dist[v]` but not `pred[v]` | Distances are right, reconstructed paths are wrong | Update both together, always |
| Using a large integer as infinity in C, Java, or NumPy int arrays | `INF + w` overflows to a negative number and creates fake short paths | Skip edges where `dist[u]` is infinite, or use a float infinity |
| Adding edges both ways for an "undirected" graph with a negative edge | A negative edge `{u, v}` becomes the cycle `u → v → u` with negative weight | Model negative-weight undirected edges with care; usually they make the problem undefined |
| Relaxing from a stale snapshot without meaning to | Results differ from expected trace | Decide on purpose whether a pass reads updated values (in place) or a copy |
In Python, math.inf + w stays inf for any finite w, and inf < inf is False. The reverse-order pass above relied on this to skip unreachable sources safely. Languages with fixed-width integers do not behave this way, so add an explicit guard:
import math
def relax_guarded(dist, pred, u, v, w):
if dist[u] == math.inf:
return False # u not reached yet; nothing to propagate
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
pred[v] = u
return True
return False
dist = [0, math.inf, math.inf]
pred = [None] * 3
print(relax_guarded(dist, pred, 1, 2, -5), dist) # False [0, inf, inf]Exercise
Start with dist = [0, inf, inf, inf] and relax these edges once, in this order: (2, 3, 1), (0, 2, 3), (0, 1, 1), (1, 2, 1), (2, 3, 1). What is dist afterward, and which edge's relaxation did nothing because its source was still at infinity?
Show answer
(2,3,1) does nothing because dist[2] is inf. (0,2,3) sets dist[2]=3. (0,1,1) sets dist[1]=1. (1,2,1) gives 1+1=2<3, so dist[2]=2 and pred[2]=1. (2,3,1) sets dist[3]=3. The final result is [0, 1, 2, 3]. The first relaxation of (2,3,1) was the one that did nothing.
Exercise
Explain, using the upper-bound property, why relaxing every edge one extra time after the distances are already correct cannot make any estimate wrong.
Show answer
Correct estimates equal δ(s, v), and by the upper-bound property no estimate can drop below δ(s, v). The test dist[u] + w < dist[v] would need dist[u] + w < δ(s, v), but dist[u] + w is the length of a real walk to v, which cannot be shorter than δ(s, v) when no negative cycle exists. So every extra relaxation fails its test and changes nothing.
Exercise
A C implementation uses INTMAX as infinity and relaxes edge (u, v, 5) with dist[u] = INTMAX and dist[v] = INT_MAX. What goes wrong, and what is the minimal fix?
Show answer
INTMAX + 5 overflows (undefined behavior, usually wrapping to a large negative number). The test then passes, and dist[v] gets a huge negative value that spreads through the graph. The minimal fix is to skip the edge when dist[u] == INTMAX before doing the addition.