Sub topic 21
Single-source shortest paths and relaxation
This chapter assumes you know basic graph terms (directed, weighted, path), Big-O notation, and the idea of a priority queue. It sets up the vocabulary and the one operation, relaxation, that Dijkstra, Bellman-Ford, and the DAG algorithm all use. The three algorithms differ only in the order in which they relax edges.
The problem
Given a weighted directed graph and a source vertex s, find the cheapest path from s to every other vertex. The weight of a path is the sum of its edge weights. The shortest-path distance δ(s, v) is the minimum weight over all paths from s to v. It is +∞ if no path exists.
Three facts shape every algorithm in this family:
- Optimal substructure. Every subpath of a shortest path is itself a shortest path. This is why building answers from smaller answers works.
- Negative edges are allowed in the problem. Some algorithms handle them and some do not.
- Negative cycles break the definition. If a cycle of negative total weight is reachable from
s, you can loop around it forever, so δ is −∞ for every vertex it can reach. When no negative cycle is reachable, some shortest path is simple, so it has at most V − 1 edges. Zero-weight cycles are harmless because you can drop them.
State kept per vertex
Each vertex v carries two values:
dist[v]is the best known path weight fromstov. It starts at ∞, exceptdist[s] = 0.pred[v]is the vertex beforevon that best path. It starts asNone. Followingpredbackwards fromvrebuilds the path.
Relaxation
To relax an edge (u, v) with weight w, ask whether going through u improves the estimate for v.
Relaxation costs O(1). It only ever lowers dist[v], and dist[v] always stays at or above the true δ(s, v), because every value it takes corresponds to a real path.
Code: relaxation and edge order
The program below relaxes the same four edges in two different orders. Both orders give the same final distances, but they need different numbers of passes.
INF = float('inf')
def init_single_source(vertices, source):
dist = {v: INF for v in vertices}
pred = {v: None for v in vertices}
dist[source] = 0
return dist, pred
def relax(u, v, w, dist, pred):
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
pred[v] = u
return True
return False
def path_to(pred, v):
path = []
while v is not None:
path.append(v)
v = pred[v]
return path[::-1]
def run(vertices, source, edges):
dist, pred = init_single_source(vertices, source)
for passes in range(1, len(vertices) + 1):
changed = False
for u, v, w in edges:
if relax(u, v, w, dist, pred):
changed = True
if not changed:
return dist, pred, passes
return dist, pred, None # still changing after V passes
V = ['A', 'B', 'C', 'D']
order1 = [('A', 'B', 4), ('A', 'C', 1), ('C', 'B', 2), ('B', 'D', 1)]
order2 = [('B', 'D', 1), ('C', 'B', 2), ('A', 'C', 1), ('A', 'B', 4)]
d1, p1, n1 = run(V, 'A', order1)
d2, p2, n2 = run(V, 'A', order2)
print(d1, n1) # {'A': 0, 'B': 3, 'C': 1, 'D': 4} 2
print(d2, n2) # {'A': 0, 'B': 3, 'C': 1, 'D': 4} 4
print(path_to(p1, 'D')) # ['A', 'C', 'B', 'D']In order 1 the edges appear along the shortest path A→C→B→D, so one pass finds everything. The second pass confirms nothing changes. In order 2 the edges appear in reverse, so each pass pushes the correct value only one edge further.
Properties you can rely on
| Property | Statement |
|---|---|
| Triangle inequality | δ(s, v) ≤ δ(s, u) + w(u, v) for every edge (u, v) |
| Upper-bound | `dist[v]` ≥ δ(s, v) at all times, and never rises once it equals δ(s, v) |
| No-path | If `v` is unreachable from `s`, `dist[v]` stays ∞ |
| Convergence | If `s ⇝ u → v` is a shortest path and `dist[u]` = δ(s, u) before relaxing (u, v), then `dist[v]` = δ(s, v) afterwards |
| Path-relaxation | If the edges of a shortest path are relaxed in path order, even with other relaxations mixed in, the last vertex ends with its correct distance |
The path-relaxation property explains the code output. A shortest path has at most V − 1 edges, so if you can relax every edge in some useful order, you finish quickly.
How the algorithms differ
| Algorithm | Edge order | Negative edges | Time |
|---|---|---|---|
| BFS | Queue order (unweighted) | Not applicable | O(V + E) |
| DAG shortest paths | Topological order of vertices | Yes | O(V + E) |
| Dijkstra | Closest unsettled vertex first | No | O((V + E) log V) with a binary heap |
| Bellman-Ford | All edges, repeated V − 1 times | Yes, and detects negative cycles | O(VE) |
Each row is a rule for choosing which edge to relax next. Later chapters cover Dijkstra and Bellman-Ford in full.
Common errors
- Forgetting to initialize. Starting
dist[s]at anything other than 0, or other vertices below ∞, breaks the upper-bound property. - Updating
distwithout updatingpred. The distances stay right but the path you rebuild is wrong. - Assuming a path with fewer edges is cheaper. In a weighted graph, A→C→B costs 3 while A→B costs 4.
- Ignoring negative cycles. Repeated relaxation never settles when a negative cycle is reachable. The
runfunction above returnsNonein that case. - Using ∞ arithmetic carelessly. In languages without a true infinity, a large sentinel plus a negative weight can look like a real distance. Skip edges whose source is still ∞.
Exercise
A graph has edges S→A (weight 2), A→B (weight 3), and S→B (weight 7). All dist values start at ∞ except dist[S] = 0. You relax the edges in the order S→B, A→B, S→A, and then in the order S→A, A→B, S→B. How many relaxations succeed in each order, and what is the final dist[B]?
Show answer
Order 1: S→B succeeds (dist[B] = 7). A→B fails because dist[A] is ∞. S→A succeeds (dist[A] = 2). That is 2 successes after one pass, and dist[B] is still 7, which is wrong. A second pass would relax A→B to 5 and add a third success. Order 2: S→A succeeds (dist[A] = 2), A→B succeeds (dist[B] = 5), and S→B fails (7 is not below 5). That is 2 successes, and dist[B] = 5 is correct after one pass. The final answer is 5 in both cases once Order 1 gets its second pass, but Order 2 matches the order of the shortest path S→A→B, so it needs only one pass.
Exercise
Why is a shortest path guaranteed to have at most V − 1 edges when no negative cycle is reachable from the source?
Show answer
A path with V or more edges must repeat a vertex, so it contains a cycle. That cycle has weight at least 0, so removing it gives a path that is no heavier. Repeating this removal leaves a simple path, which visits each vertex at most once and so has at most V − 1 edges.