Bellman-Ford Algorithm — Working, Example and Applications
The Bellman-Ford algorithm computes the shortest path from a single source vertex to all other vertices in a weighted graph. Unlike Dijkstra's algorithm, Bellman-Ford can correctly handle graphs with negative edge weights, and it can also detect negative weight cycles.
How It Works
- Initialize the distance to the source as 0 and all other vertices as infinity.
- Relax every edge — if going through an edge gives a shorter path to a vertex, update its distance.
- Repeat the relaxation process for (V - 1) iterations, where V is the number of vertices.
- Perform one more pass; if any distance can still be improved, a negative weight cycle exists.
def bellman_ford(edges, num_vertices, source):
distance = [float('inf')] * num_vertices
distance[source] = 0
for _ in range(num_vertices - 1):
for u, v, weight in edges:
if distance[u] != float('inf') and distance[u] + weight < distance[v]:
distance[v] = distance[u] + weight
for u, v, weight in edges:
if distance[u] != float('inf') and distance[u] + weight < distance[v]:
raise ValueError("Graph contains a negative weight cycle")
return distance
Worked Example
Consider a graph with edges (A→B, 4), (A→C, 5), (B→C, -3), (C→D, 2). Starting from A, Bellman-Ford relaxes each edge repeatedly: distance to B becomes 4, distance to C is improved to 1 via B (4 + -3), and distance to D becomes 3 (1 + 2). This shows how the algorithm correctly handles the negative edge B→C.
Complexity
| Metric | Value |
|---|---|
| Time | O(V * E) |
| Space | O(V) |
Applications
- Routing protocols such as RIP (Routing Information Protocol).
- Detecting arbitrage opportunities in currency exchange graphs.
- Network flow problems where edge costs can be negative.
Why V − 1 Rounds Are Always Enough
A shortest path without cycles visits each vertex at most once, so it can contain at most V − 1 edges. After the first full round of relaxation, every shortest path that uses one edge is correct. After the second round, every path with up to two edges is correct, and so on. By round V − 1 every possible simple path has been accounted for.
This also explains the final check. If a distance still drops in round V, the only way that can happen is a cycle whose total weight is negative, because going around it again keeps making the path cheaper.
A negative cycle in action
Take edges (A→B, 1), (B→C, 2), (C→D, -4) and (D→B, 1). The loop B→C→D→B adds up to 2 − 4 + 1 = −1. Every trip around it lowers the cost of reaching B, C and D, so there is no true shortest distance to them. The algorithm reports the cycle instead of returning misleading numbers.
Recovering the Path and Stopping Early
The basic version returns only distances. In real problems you usually need the route, and you can often finish well before V − 1 rounds.
def bellman_ford_path(edges, n, source):
INF = float('inf')
dist = [INF] * n
parent = [None] * n
dist[source] = 0
for _ in range(n - 1):
changed = False
for u, v, w in edges:
if dist[u] != INF and dist[u] + w < dist[v]:
dist[v] = dist[u] + w
parent[v] = u
changed = True
if not changed: # nothing improved, answers are final
break
for u, v, w in edges:
if dist[u] != INF and dist[u] + w < dist[v]:
raise ValueError("Negative weight cycle reachable from source")
return dist, parent
def build_path(parent, target):
path = []
while target is not None:
path.append(target)
target = parent[target]
return path[::-1]
edges = [(0, 1, 4), (0, 2, 5), (1, 2, -3), (2, 3, 2)]
dist, parent = bellman_ford_path(edges, 4, 0)
print(dist) # [0, 4, 1, 3]
print(build_path(parent, 3)) # [0, 1, 2, 3]
The parent list stores which vertex last improved each distance. Walking it backwards from the target and reversing the list gives the route A → B → C → D from the earlier example.
Choosing Between Shortest-Path Algorithms
| Algorithm | Negative edges | Detects negative cycles | Time | Best fit |
|---|---|---|---|---|
| Dijkstra (binary heap) | No | No | O((V + E) log V) | Road maps, non-negative costs |
| Bellman-Ford | Yes | Yes | O(V × E) | Single source with negative weights |
| Floyd-Warshall | Yes | Yes | O(V³) | All pairs on small dense graphs |
If every weight is zero or positive, Dijkstra is almost always the faster choice. Reach for Bellman-Ford when weights can be negative or when you specifically need to prove that no negative cycle exists.
Common Implementation Errors
- Treating undirected edges carelessly. An undirected edge with negative weight acts as a two-edge negative cycle, so Bellman-Ford will always flag it.
- Dropping the infinity check. In languages with fixed-size integers, adding a weight to a large sentinel value can overflow and create fake short paths.
- Skipping the final pass. Without it, a graph with a negative cycle returns numbers that look valid but are wrong.
- Thinking edge order changes the answer. It only affects how many rounds are needed, not the final distances.