Sub topic 3
Edge Relaxation: Improving Distance Estimates
This chapter assumes you know basic graph terms, can read an adjacency list stored as a Python dict, and are comfortable with loops and functions. It uses the single-source shortest path setup from the previous chapter: one source vertex, non-negative edge weights, and a distance to find for every other vertex.
Tentative Distances
Dijkstra's algorithm does not know the shortest distances at the start. It keeps a guess for each vertex instead. This guess is called a tentative distance, written dist[v]. It begins as:
dist[source] = 0, because reaching the source costs nothing.dist[v] = infinityfor every other vertex, because no path to it has been found yet.
The algorithm only ever lowers these guesses. It also guarantees that each guess is the length of a real path from the source, or infinity. That means dist[v] is always an upper bound on the true shortest distance. The guess can be too high, but it is never too low.
The Relaxation Step
Relaxing an edge u → v with weight w asks one question: is the path to u followed by this edge cheaper than the best path to v known so far?
- If
dist[u] + w < dist[v], setdist[v] = dist[u] + wand recorduas the predecessor ofv. - Otherwise, change nothing.
The name comes from picturing dist[v] as a tight constraint. Finding a shorter route loosens, or relaxes, that constraint.
Relaxation in Code
The script below relaxes each edge once, in a fixed order that does not follow any strategy. Watch what happens to D.
INF = float("inf")
def relax(u, v, w, dist, prev):
"""Try to improve dist[v] using edge u -> v of weight w."""
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
prev[v] = u
return True
return False
graph = {
"A": [("B", 4), ("C", 1)],
"C": [("B", 2), ("D", 5)],
"B": [("D", 1)],
"D": [],
}
dist = {v: INF for v in graph}
dist["A"] = 0
prev = {}
edges = [("A", "B", 4), ("A", "C", 1), ("B", "D", 1), ("C", "B", 2), ("C", "D", 5)]
for u, v, w in edges:
changed = relax(u, v, w, dist, prev)
status = "updated" if changed else "no change"
print(f"{u}->{v} (w={w}): {status}, dist[{v}] = {dist[v]}")
print(dist) # {'A': 0, 'C': 1, 'B': 3, 'D': 5}
relax("B", "D", 1, dist, prev) # relax B->D a second time
print(dist["D"]) # 4The output, step by step:
| Edge | Check | Result |
|---|---|---|
| A→B (4) | 0 + 4 < ∞ | dist[B] = 4 |
| A→C (1) | 0 + 1 < ∞ | dist[C] = 1 |
| B→D (1) | 4 + 1 < ∞ | dist[D] = 5 |
| C→B (2) | 1 + 2 < 4 | dist[B] = 3 |
| C→D (5) | 1 + 5 < 5 is false | no change |
After one pass, dist["D"] is 5, but the true answer is 4 (A→C→B→D). The edge B→D was relaxed while dist["B"] was still 4, before B's estimate improved to 3. Relaxing B→D again fixes the result.
Common Errors
- Using
Noneor 0 for "unreached."None + wraises aTypeError. A 0 makes every vertex look already reached. Usefloat("inf"), which compares and adds correctly. - Using a large integer such as
sys.maxsizeas infinity. Adding a weight to it gives a value larger than "infinity," and that can cause wrong comparisons in code that mixes types or ports to fixed-width integers. - Forgetting to update
prev[v]. The distances come out right, but you can no longer recover the path. - Writing
<=instead of<. Ties then overwrite predecessors for no gain, and in heap-based code they push extra entries onto the heap.
Exercise
Starting from dist = {A: 0, B: ∞, C: ∞} with no predecessors, relax these edges in order: A→B (weight 7), A→C (weight 2), C→B (weight 3), A→B (weight 7). Give the final dist values and prev map, and say which relaxations changed something.
Show answer
A→B sets dist[B] = 7, prev[B] = A. A→C sets dist[C] = 2, prev[C] = A. C→B checks 2 + 3 = 5 < 7, so dist[B] = 5 and prev[B] = C. The second A→B checks 0 + 7 < 5, which is false, so nothing changes. Final: dist = {A: 0, B: 5, C: 2}, prev = {B: C, C: A}. The first three relaxations changed something; the fourth did not.
Exercise
Explain why dist[v] can never fall below the true shortest distance from the source to v during relaxation.
Show answer
Each update sets dist[v] = dist[u] + w, where dist[u] is the length of a real path to u, or the source's 0. Adding edge u→v makes it the length of a real path to v. The shortest distance is no longer than any real path, so dist[v] stays at or above it.