When a shortcut has a negative price.
Relax edges repeatedly and detect a reachable cycle that makes shortest distance undefined.
01 Model the idea
Bellman–Ford permits negative edge weights. After k full passes, every best path using at most k edges has been accounted for; in-place updates may also propagate farther within one pass. Any shortest simple path has at most V−1 edges. If a reachable distance can still improve afterward, a reachable negative cycle prevents finite shortest distances for affected destinations.
Distances are best-known upper bounds from valid discovered walks.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
INITIALISE source to zero and others to infinity
RELAX every edge up to V−1 times
CHECK for a further reachable improvement| Stage | A | B | C |
|---|---|---|---|
| Initial | 0 | ∞ | ∞ |
| First full pass | 0 | 4 | 2 |
| Converged | 0 | 4 | 2 |
03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
def bellman_ford(vertices, edges, start):
distance = {node: float("inf") for node 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
print(bellman_ford(["A", "B", "C"], [("A", "B", 4), ("A", "C", 5), ("B", "C", -2)], "A")){'A': 0, 'B': 4, 'C': 2}- 1
Every edge considers a possible improvement through its source. Unreachable sources remain infinite and cannot establish a route.
- 2
The early-exit flag stops when a full pass changes nothing. It does not change the worst-case O(VE) bound.
- 3
The final pass detects a negative cycle reachable from the chosen source. A negative cycle elsewhere in a disconnected graph is not reported by this single-source check.
04 Count the cost
O(VE)
O(V) distance state, excluding stored edges
Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.
05 Your next move
Detect a reachable negative cycle in a two-vertex example using the full relaxation rule.
Reveal one possible solution +
vertices = ["A", "B"]
edges = [("A", "B", 1), ("B", "A", -2)]
distance = {"A": 0, "B": float("inf")}
for _ in range(len(vertices) - 1):
for u, v, w in edges: distance[v] = min(distance[v], distance[u] + w)
print(any(distance[u] + w < distance[v] for u, v, w in edges))06 Check your reasoning
What makes finite shortest distance impossible for affected vertices?
Understand it. Then own it.
Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.