Sub topic 15
Single-Source Shortest Paths and Relaxation
Prerequisites and problem statement
Assume you know weighted graphs, adjacency lists, queues, and asymptotic notation. A single-source shortest-path (SSSP) problem asks for the minimum-cost path from one source vertex \(s\) to every reachable vertex.
For an edge \((u,v)\) with weight \(w\), a path to \(v\) through \(u\) has cost:
\[ \text{distance}[u] + w \]
If this cost is smaller than the current estimate for \(v\), we improve the estimate. This operation is called relaxation:
\[ \text{distance}[v] \leftarrow \min(\text{distance}[v],\text{distance}[u]+w) \]
Initially, the source has distance zero. Every other distance is infinity because no path is known.
Relaxing edges
def relax_all_edges(graph, source):
distance = {u: float("inf") for u in graph}
distance[source] = 0
changed = True
while changed:
changed = False
for u in graph:
for v, weight in graph[u]:
candidate = distance[u] + weight
if candidate < distance[v]:
distance[v] = candidate
changed = True
return distance
graph = {
"A": [("B", 4), ("C", 2)],
"B": [("D", 3)],
"C": [("B", 1), ("D", 5)],
"D": []
}
print(relax_all_edges(graph, "A"))The result is {'A': 0, 'B': 3, 'C': 2, 'D': 6}. The path from A to B improves from 4 to 3 through C. The path from A to D then improves to 6 through B.
A relaxation is safe because a newly discovered path can only lower an estimate. Once an algorithm knows that no remaining path can improve an estimate, that estimate is final.
Why the algorithm matters
Different SSSP algorithms control the order in which edges are relaxed.
| Graph condition | Suitable method | Typical time |
|---|---|---|
| Non-negative weights | Dijkstra | \(O((V+E)\log V)\) |
| Negative edges allowed | Bellman-Ford | \(O(VE)\) |
| Negative cycle reachable | No finite shortest paths | Detection required |
A shortest path never needs a cycle with nonnegative total weight. Removing such a cycle does not increase the path cost. If a reachable negative cycle exists, repeatedly traversing it makes the cost decrease without limit, so a finite shortest distance does not exist.
Relaxation rounds
Bellman-Ford uses repeated rounds over every edge. After one complete round, it correctly finds every shortest path that uses at most one edge. After two rounds, it handles paths using at most two edges. Since a simple shortest path has at most \(V-1\) edges, \(V-1\) rounds are enough. A further improving relaxation indicates a reachable negative cycle.
Exercise
Why does Bellman-Ford perform at most V-1 full relaxation rounds before checking for a negative cycle?
Show answer
A simple shortest path uses at most V-1 edges. Each round can extend the correctly handled path length by one edge.