The problem
Four places joined by one-way roads. Each road has a cost; the road from b to a costs −4, a refund. We want the cheapest total cost from s to every place. A negative road is allowed; a loop that pays back is not.
Dijkstra's algorithm settles the closest place first and never revisits it. It settles a at 2, then c at 3. But s→b→a→c costs 5 − 4 + 1 = 2. The refund comes too late: a (really 1) and c (really 2) are both wrong.
Relaxing in rounds
Start with d[s] = 0 and every other place at ∞, meaning not reached yet. Relaxing a road u→v with cost w asks: is d[u] + w less than d[v]? If yes, v gets that cheaper total. That is the only move.
Bellman-Ford tries every road in one fixed list order: a→c, b→a, s→a, s→b. a and b are still at ∞, so their roads do nothing yet. s→a gives a = 2, and s→b gives b = 5.
Same list again. a→c gives c = 2 + 1 = 3. b→a gives 5 − 4 = 1, cheaper than 2, so a drops to 1. Unlike in Dijkstra, a place can get cheaper again and again.
a→c now gives 1 + 1 = 2, so c drops from 3 to 2. Nothing else changes. The best route s→b→a→c has 3 roads, and it took 3 rounds to carry the news along it.
Proof and checks
After round k, every place whose cheapest route uses at most k roads is right. A route with no loop has at most V − 1 roads (V = number of places). Each round tries all E roads, so the work is O(V·E).
Try every road once more. Nothing gets cheaper, so the answers are final: s 0, a 1, b 5, c 2. If a whole round ever changes nothing, the loop can also stop early.
Add a road c→b costing 2. The loop b→a→c→b costs −4 + 1 + 2 = −1, so every lap is cheaper and no cheapest total exists. After 3 rounds, the extra pass still improves a: a negative cycle.
The whole function in Python
def bellman_ford(nodes, edges, s):
d = {v: float("inf") for v in nodes}
d[s] = 0
V = len(nodes)
for _ in range(V - 1):
for u, v, w in edges:
if d[u] + w < d[v]:
d[v] = d[u] + w
for u, v, w in edges:
if d[u] + w < d[v]:
return None
return d
edges = [("a", "c", 1), ("b", "a", -4), ("s", "a", 2), ("s", "b", 5)]
print(bellman_ford("sabc", edges, "s"))
What happens
# step 1/9 · Roads with a refund
a directed graph with edge weights (costs)
a -> c cost 1
b -> a cost -4
s -> a cost 2
s -> b cost 5
the same roads in Python, as a list of (u, v, w):
edges = [("a", "c", 1), ("b", "a", -4), ("s", "a", 2), ("s", "b", 5)]
The bound comes from MIT 6.006 and CLRS §22.1: with no negative cycle, a cheapest route never repeats a place, so it has at most V − 1 roads, and round k fixes every place whose cheapest route has k roads or fewer. The list order only changes how many rounds are really needed, never the answer. This example lists the roads in a bad order on purpose (a→c first), so the news needs all 3 rounds. In the order s→b, b→a, a→c, s→a, one round would already be enough.