Graphs and shortest paths · Algorithm 10 of 15
Bellman–Ford
Relax every edge repeatedly to handle negative weights. Citation needed
The whole, before the parts
Bellman–Ford finds shortest distances from a starting point while allowing connections with negative costs. It also checks for reachable loops that keep reducing cost, where a finite shortest distance may not exist. Citation needed
Terminology and core concepts
Bellman–Ford finds shortest distances from one source even when some edges have negative weights. Repeat a pass over every edge, accepting any improvement. A shortest route without repeated vertices uses at most V - 1 edges, so V - 1 passes suffice when no reachable negative cycle exists. A negative cycle is a loop whose weights sum to a negative number; repeatedly going around it prevents a finite shortest distance for vertices reachable from it. Citation needed
Learning path
Trace an example
vertices: A, B, C; source A edge order: B -> C (-3), A -> C (4), A -> B (2) start A:0 B:infinity C:infinity pass 1 A:0 B:2 C:4 pass 2 A:0 B:2 C:-1 check no edge improves: done
Implement it in Python
Read the loop alongside the trace, then run this self-contained example with Python 3. The assertions show expected results. Inputs use ordinary Python lists and dictionaries; comparisons and numeric operations are assumed to behave normally. Citation needed
def bellman_ford(vertices, edges, start):
# vertices contains every endpoint and start; edges are (from, to, weight).
distance = {v: float('inf') for v in vertices}
distance[start] = 0
for _ in range(len(vertices) - 1):
changed = False
for u, v, weight in edges:
if distance[u] != float('inf') and distance[u] + weight < distance[v]:
distance[v] = distance[u] + weight
changed = True
if not changed:
break
for u, v, weight in edges:
if distance[u] != float('inf') and distance[u] + weight < distance[v]:
raise ValueError('Reachable negative cycle')
return distance
edges = [('B', 'C', -3), ('A', 'C', 4), ('A', 'B', 2)]
assert bellman_ford(['A', 'B', 'C'], edges, 'A') == {'A': 0, 'B': 2, 'C': -1}
assert bellman_ford(['A', 'B'], [], 'A')['B'] == float('inf')Citation needed
Analyze the cost
There are at most V - 1 full relaxation passes and one detection pass, so time is O(VE + V) including initialization, conventionally O(VE) when edges are present. Extra distance storage is O(V). Early stopping helps some inputs without improving the worst-case bound. Citation needed
A mistake to watch for
Only a negative cycle reachable from the source invalidates this source’s result. The graph must list all vertices, including isolated ones. Use finite numeric edge weights. Citation needed
Practice and recall
-
Add edge C to B with weight 1 to the example. Why is there no finite shortest distance to B?
Work it out before opening the solution. Citation needed
Show the reasoning
- The cycle B to C to B has weight -3 + 1 = -2.
- A can reach B, so the cycle is reachable.
- Each repetition lowers the cost by 2; the final detection pass finds another improvement.
Citation needed
- What does an improving edge after V - 1 passes reveal?
- A negative cycle reachable from the source. Citation needed
To check your understanding, reproduce the implementation without looking, explain why its main step is safe, and test an edge case before moving to the next algorithm. Citation needed
Sources
- MIT OpenCourseWare: Introduction to Algorithms — lecture notes — further study of the underlying algorithm and analysis.
- Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein, Introduction to Algorithms — correctness arguments and complexity analysis.