Sub topic 5
The Bellman-Ford Algorithm
This chapter assumes you know what edge relaxation is (from the previous chapter), can read Python, and are comfortable with Big-O notation. It covers the algorithm itself: how it is set up, how a round works, what a trace looks like, and the implementation mistakes people make most often. Later chapters cover why V-1 rounds are enough, the extra pass that detects negative cycles, early termination, and path reconstruction. This chapter mentions them only where it needs to.
The Idea in One Paragraph
Bellman-Ford solves the single-source shortest path problem on a weighted directed graph, and negative edge weights are allowed. It keeps a tentative distance dist[v] for every vertex. It then relaxes every edge in the graph, in any fixed order, and repeats that full sweep V-1 times, where V is the number of vertices. Dijkstra's algorithm picks the closest unfinished vertex and treats its distance as final. Bellman-Ford never treats any distance as final until all rounds are done. That choice is the reason it tolerates negative edges, and it is also the reason it is slower.
The Algorithm Step by Step
- Set
dist[source] = 0anddist[v] = ∞for every other vertex. Setpred[v] = Nonefor all vertices. - Repeat V-1 times:
- For each edge
(u, v, w): ifdist[u] + w < dist[v], setdist[v] = dist[u] + wandpred[v] = u. - Return
distandpred.
The pred array records which vertex last improved each distance. The chapter on recovering paths turns it into actual routes.
A Runnable Core Implementation
This version adds a trace flag so you can watch the distances change after each round.
import math
def bellman_ford_core(n, edges, source, trace=False):
# 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 round_no in range(1, n): # exactly n - 1 rounds
for u, v, w in edges:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
pred[v] = u
if trace:
print(f"after round {round_no}: {dist}")
return dist, pred
edges = [(0, 1, 4), (0, 2, 5), (1, 2, -3), (2, 3, 4), (1, 3, 6)]
print("Forward edge order:")
dist, pred = bellman_ford_core(4, edges, 0, trace=True)
print("dist =", dist, "pred =", pred)
print("Reversed edge order:")
dist, pred = bellman_ford_core(4, list(reversed(edges)), 0, trace=True)
print("dist =", dist, "pred =", pred)Output:
Forward edge order:
after round 1: [0, 4, 1, 5]
after round 2: [0, 4, 1, 5]
after round 3: [0, 4, 1, 5]
dist = [0, 4, 1, 5] pred = [None, 0, 1, 2]
Reversed edge order:
after round 1: [0, 4, 5, inf]
after round 2: [0, 4, 1, 9]
after round 3: [0, 4, 1, 5]
dist = [0, 4, 1, 5] pred = [None, 0, 1, 2]Tracing the Example
The graph has four vertices. The shortest route from 0 to 3 is 0 → 1 → 2 → 3, with weight 4 + (-3) + 4 = 5. The direct edge 0 → 2 costs 5, but the detour through 1 costs only 1, because the negative edge 1 → 2 more than pays for the extra hop.
Forward order: one round is enough
Within round 1, each relaxation can use a distance that was improved earlier in the same round:
| Edge relaxed | Check | Result |
|---|---|---|
| (0, 1, 4) | 0 + 4 < ∞ | dist[1] = 4, pred[1] = 0 |
| (0, 2, 5) | 0 + 5 < ∞ | dist[2] = 5, pred[2] = 0 |
| (1, 2, -3) | 4 - 3 = 1 < 5 | dist[2] = 1, pred[2] = 1 |
| (2, 3, 4) | 1 + 4 = 5 < ∞ | dist[3] = 5, pred[3] = 2 |
| (1, 3, 6) | 4 + 6 = 10 < 5? no | unchanged |
The edges happen to be listed in path order, so round 1 finishes the whole job. Rounds 2 and 3 change nothing.
Reversed order: the worst case
With the edges reversed, each round can carry correct information only one more edge along the shortest path:
| Round | dist after the round | What became correct |
|---|---|---|
| 1 | [0, 4, 5, ∞] | Paths with 1 edge: vertex 1 |
| 2 | [0, 4, 1, 9] | Paths with up to 2 edges: vertex 2 |
| 3 | [0, 4, 1, 5] | Paths with up to 3 edges: vertex 3 |
In round 2, vertex 3 gets 9 (via the stale value dist[2] = 5) before vertex 2 is corrected to 1 later in that round. Round 3 fixes vertex 3. The final answer is the same for both orders. Only the number of rounds that do useful work differs.
Cost
| Resource | Cost | Reason |
|---|---|---|
| Time | O(V · E) | V-1 rounds, each relaxing all E edges |
| Extra space | O(V) | `dist` and `pred` arrays |
| Input format | Edge list | Each round only iterates over edges, so no adjacency structure is needed |
On a dense graph, E is close to V², so the time approaches O(V³). Dijkstra with a binary heap runs in O((V + E) log V). Bellman-Ford is therefore the tool to use when negative weights force you to, not a general replacement for Dijkstra.
Common Errors and Edge Cases
Integer infinity overflow
Python's math.inf + w stays inf, and inf < inf is False, so unreachable vertices never relax their neighbors. In languages with fixed-width integers, INT_MAX + w overflows when w is positive. When w is negative, INT_MAX + w gives a finite value, so an unreachable vertex seems to offer a real path. Guard the check explicitly:
import math
def relax(dist, pred, u, v, w):
# Explicit guard, required when "infinity" is a large integer sentinel
if dist[u] != math.inf and dist[u] + w < dist[v]:
dist[v] = dist[u] + w
pred[v] = u
return True
return False
dist = [0, math.inf, math.inf]
pred = [None, None, None]
print(relax(dist, pred, 1, 2, -5), dist) # False [0, inf, inf]
print(relax(dist, pred, 0, 1, 3), dist) # True [0, 3, inf]Updating in place versus copying
The core implementation updates dist in place, so a round can use values set earlier in the same round. That is correct and often faster. It breaks one common variant: "shortest path using at most k edges" (for example, a cheapest flight with at most k stops). For that variant, each round must read from a copy of the previous round's distances. Otherwise, one round can chain several edges together.
import math
def shortest_with_at_most_k_edges(n, edges, source, k):
dist = [math.inf] * n
dist[source] = 0
for _ in range(k):
prev = dist[:] # read only last round's values
for u, v, w in edges:
if prev[u] + w < dist[v]:
dist[v] = prev[u] + w
return dist
edges = [(0, 1, 4), (0, 2, 5), (1, 2, -3), (2, 3, 4), (1, 3, 6)]
print(shortest_with_at_most_k_edges(4, edges, 0, 1)) # [0, 4, 5, inf]
print(shortest_with_at_most_k_edges(4, edges, 0, 2)) # [0, 4, 1, 9]Undirected graphs with negative edges
If you model an undirected edge {a, b} with weight -2 as two directed edges, you create the cycle a → b → a with weight -4. That is a negative cycle, and shortest paths stop being defined. Bellman-Ford is a directed-graph algorithm. Undirected graphs with negative edges need different techniques.
Other cases that work without special handling
- Unreachable vertices keep
dist = infandpred = None. - Parallel edges between the same pair are fine. The cheaper edge wins.
- A non-negative self-loop never relaxes anything. A negative self-loop is a negative cycle.
- If the graph has a negative cycle reachable from the source, the V-1 rounds finish without any error but return meaningless distances. The extra detection pass in a later chapter catches this.
The Reference Implementation
The tutorial's full version adds two refinements to the core loop. It stops early when a round changes nothing, and it runs one final pass that raises an error if a negative cycle is reachable. Both get their own chapters.
import math
def bellman_ford(n, edges, source):
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]Exercises
Exercise
Run bellmanfordcore on the graph with edges [(0, 1, 2), (1, 2, -1), (2, 3, 3), (0, 3, 6)], source 0, listed in that order. What is dist after round 1, and what is the final pred array?
Show answer
Round 1 relaxes 0→1 (dist[1]=2), then 1→2 (dist[2]=1), then 2→3 (dist[3]=4). Then 0→3 gives 6, which is not less than 4. So dist after round 1 is [0, 2, 1, 4], and later rounds change nothing. The final pred is [None, 0, 1, 2].
Exercise
For a path graph 0→1→2→...→(V-1), which order of the edge list forces Bellman-Ford to use all V-1 rounds, and which order finishes in one round?
Show answer
Listing edges from the end of the path backward ((V-2, V-1) first, (0, 1) last) moves correct distances forward by only one vertex per round, so all V-1 rounds are needed. Listing them in path order ((0, 1) first) finishes everything in round 1.
Exercise
A C implementation uses INF = INT_MAX and the check dist[u] + w < dist[v] with no guard. Vertex u is unreachable, and the edge u→v has weight -10. What goes wrong?
Show answer
INTMAX - 10 is a finite value smaller than INTMAX, so the check passes. dist[v] gets a fake finite distance and pred[v] = u, which reports a path from an unreachable vertex. Add the guard dist[u] != INF before relaxing.