Bellman-Ford Algorithm
The Bellman-Ford algorithm finds the shortest paths from one start vertex, like Dijkstra's algorithm, but it also works when some edges have negative weights. As a bonus, it can tell when a negative cycle makes shortest paths meaningless. The price is speed: O(V · E) instead of Dijkstra's O((V + E) log V).
Negative weights are not exotic. In a currency exchange graph, using -log(rate) as the edge weight turns "find a profitable sequence of trades" into "find a negative cycle".
The idea
Bellman-Ford doesn't try to be clever about the order. It simply relaxes every edge, and repeats that V - 1 times:
- Set
dist[start] = 0, all others to infinity. - Repeat
V - 1times: for every edgeu → vwith weightw, ifdist[u] + w < dist[v], setdist[v] = dist[u] + w. - Check every edge once more. If any edge can still be relaxed, there is a negative cycle.
Why V - 1 rounds? A shortest path without cycles uses at most V - 1 edges. After round k, every vertex whose shortest path has at most k edges already has its final distance. So after V - 1 rounds, all of them do.
Implementation
Our graph has 5 vertices and one negative edge, C → B with weight -3:
S ──6──▶ B ──2──▶ D
│ ▲ ▲
4 -3 │
▼ │ │
A ──1──▶ C ───5───┘import math
vertices = ["S", "A", "B", "C", "D"]
edges = [("S", "A", 4), ("S", "B", 6), ("A", "C", 1),
("C", "B", -3), ("B", "D", 2), ("C", "D", 5)]
def bellman_ford(vertices, edges, start):
dist = {v: math.inf for v in vertices}
prev = {v: None for v in vertices}
dist[start] = 0
for round_no in range(1, len(vertices)):
changed = False
for u, v, w in edges:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
prev[v] = u
changed = True
print(f"after round {round_no}: {dist}")
if not changed:
print("no changes, stopping early")
break
for u, v, w in edges:
if dist[u] + w < dist[v]:
raise ValueError("graph contains a negative cycle")
return dist, prev
dist, prev = bellman_ford(vertices, edges, "S")after round 1: {'S': 0, 'A': 4, 'B': 2, 'C': 5, 'D': 4}
after round 2: {'S': 0, 'A': 4, 'B': 2, 'C': 5, 'D': 4}
no changes, stopping early
In round 1 the edges happen to be processed in a helpful order, so most distances are already final: B improves from 6 to 2 via S → A → C → B (4 + 1 - 3). Round 2 changes nothing, so we stop early. That early exit is a common and safe optimisation.
Order matters (but not for correctness)
If the edges come in an unlucky order, information travels only one edge further per round. Here the edges are listed backwards along the chain S → A → B → C → D, so each round finalises just one more vertex:
import math
def bellman_ford_rounds(vertices, edges, start):
dist = {v: math.inf for v in vertices}
dist[start] = 0
for r in range(1, len(vertices)):
changed = False
for u, v, w in edges:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
changed = True
print(f"round {r}: {[dist[v] for v in vertices]}")
if not changed:
break
chain = ["S", "A", "B", "C", "D"]
backwards = [("C", "D", 1), ("B", "C", 1), ("A", "B", 1), ("S", "A", 1)]
bellman_ford_rounds(chain, backwards, "S")round 1: [0, 1, inf, inf, inf]
round 2: [0, 1, 2, inf, inf]
round 3: [0, 1, 2, 3, inf]
round 4: [0, 1, 2, 3, 4]
This is the worst case: it really needs all V - 1 = 4 rounds.
Detecting a negative cycle
If the graph has a cycle with a negative total weight that can be reached from the start, distances keep shrinking forever. The extra check after V - 1 rounds catches this: in a graph without negative cycles nothing can improve any more.
import math
def bellman_ford(vertices, edges, start):
dist = {v: math.inf for v in vertices}
dist[start] = 0
for _ in range(len(vertices) - 1):
for u, v, w in edges:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
bad = [(u, v) for u, v, w in edges if dist[u] + w < dist[v]]
return dist, bad
vertices = ["S", "A", "B", "C"]
edges = [("S", "A", 1), ("A", "B", 2), ("B", "C", -4), ("C", "A", 1)] # A->B->C->A sums to -1
dist, bad = bellman_ford(vertices, edges, "S")
print("still relaxable:", bad)
print("negative cycle!" if bad else dist)still relaxable: [('A', 'B')]
negative cycle!
The cycle A → B → C → A has total weight 2 - 4 + 1 = -1, so every lap makes the distances smaller.
Rebuilding a path
As with Dijkstra, the prev table gives the routes:
import math
vertices = ["S", "A", "B", "C", "D"]
edges = [("S", "A", 4), ("S", "B", 6), ("A", "C", 1),
("C", "B", -3), ("B", "D", 2), ("C", "D", 5)]
dist = {v: math.inf for v in vertices}
prev = {v: None for v in vertices}
dist["S"] = 0
for _ in range(len(vertices) - 1):
for u, v, w in edges:
if dist[u] + w < dist[v]:
dist[v], prev[v] = dist[u] + w, u
def route(v):
return route(prev[v]) + [v] if v else []
for v in ["B", "D"]:
print(v, dist[v], " -> ".join(route(v)))B 2 S -> A -> C -> B
D 4 S -> A -> C -> B -> D
Dijkstra vs Bellman-Ford
| Dijkstra | Bellman-Ford | |
|---|---|---|
| Negative weights | not allowed | allowed |
| Detects negative cycles | no | yes |
| Strategy | greedy: finish the closest vertex | relax all edges V - 1 times |
| Time | O((V + E) log V) |
O(V · E) |
| Typical use | maps, routing with costs ≥ 0 | graphs with negative costs, distance-vector routing (RIP) |
Test yourself
How many rounds of relaxing all edges does Bellman-Ford need in the worst case for V vertices?
- 1
- log V
- V - 1
- E
How does Bellman-Ford detect a negative cycle?
- A distance becomes zero
- An edge can still be relaxed after V - 1 rounds
- It visits a vertex twice
- The graph has a negative edge
When is it worth using Bellman-Ford instead of Dijkstra?
- When all weights are positive
- When some weights are negative
- When the graph is unweighted
- Never; it is always slower