Sub topic 5
The Bellman-Ford Algorithm
This chapter assumes you know edge relaxation and what a negative cycle is from earlier chapters. You should also be able to read basic Python and Big-O notation. Here we put relaxation into a complete single-source algorithm.
The working model
Bellman-Ford finds the shortest distance from one source vertex to every other vertex. Edges may have negative weights. The idea is simple. You relax every edge in the graph, which is one pass, and you repeat the pass V-1 times, where V is the number of vertices.
Bellman-Ford does not pick vertices in a clever order, which is how it differs from Dijkstra. Dijkstra commits to a vertex's distance once and never revisits it, and a later negative edge can make that choice wrong. Bellman-Ford never commits. Every pass gives every edge another chance to improve a distance.
Implementation
import math
def bellman_ford(n, edges, source):
# n vertices numbered 0..n-1; edges is a list of (u, v, w) tuples
dist = [math.inf] * n
pred = [None] * n
dist[source] = 0
for _ in range(n - 1):
changed = False
for u, v, w in edges:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
pred[v] = u
changed = True
if not changed:
break
for u, v, w in edges:
if dist[u] + w < dist[v]:
raise ValueError('negative cycle reachable from source')
return dist, pred
edges = [(0, 1, 4), (0, 2, 5), (1, 2, -3), (2, 3, 4), (1, 3, 6)]
dist, pred = bellman_ford(4, edges, 0)
print(dist) # [0, 4, 1, 5]The early break and the final check pass each get their own chapter later. The pred array records which vertex last improved each distance, and a later chapter uses it to rebuild paths.
Tracing the example
With this edge order, the first pass already reaches the final answer:
| Edge relaxed | dist after |
|---|---|
| (0, 1, 4) | [0, 4, ∞, ∞] |
| (0, 2, 5) | [0, 4, 5, ∞] |
| (1, 2, -3) | [0, 4, 1, ∞] |
| (2, 3, 4) | [0, 4, 1, 5] |
| (1, 3, 6) | [0, 4, 1, 5] (10 is not less than 5) |
The second pass changes nothing, so the loop exits early. If the edges came in a worse order, the algorithm would need more passes. The final distances would be the same.
Cost
Each pass touches all E edges, and there are at most V-1 passes. The time is O(V·E) and the extra space is O(V). On a dense graph, where E is close to V², that grows to O(V³).
Common errors
- Treating an undirected graph as two directed edges. An undirected edge with negative weight becomes a two-edge negative cycle, u → v → u. Bellman-Ford will report that cycle.
- Guarding against infinity by hand. In Python,
math.inf + wstaysmath.infeven when w is negative, so unreachable vertices never relax anything. If you use a large integer like10**9as infinity, you must skip vertices whose distance is still that value. Otherwise a negative edge can "improve" an unreachable vertex. - Off-by-one in the pass count. You need V-1 passes for the distances, plus a separate check pass. Running V passes and returning the result skips the cycle check.
Exercise
Run bellman_ford on the same graph with the edge list reversed: [(1, 3, 6), (2, 3, 4), (1, 2, -3), (0, 2, 5), (0, 1, 4)]. How many passes change at least one distance, and what is the final dist?
Show answer
All three passes change something. Pass 1 gives [0, 4, 5, ∞]. Pass 2 gives [0, 4, 1, 9]. Pass 3 lowers dist[3] to 5. The final dist is [0, 4, 1, 5], the same as before, and the check pass finds no negative cycle.
Exercise
A graph has 1,000 vertices and 5,000 edges. What is the worst-case number of edge relaxations, counting the check pass?
Show answer
(V-1)·E + E = 999 · 5,000 + 5,000 = 5,000,000 relaxations.