asc1for _ in range(V - 1):2 for u, v, w in edges:3 if d[u] + w < d[v]:4 d[v] = d[u] + w5for u, v, w in edges:6 if d[u] + w < d[v]:7 return None8return dbroundroad1−4252
Places: the front number is d, the cheapest total from s so farRoads: one-way arrows with their cost; red is negativeToken: d[u] + w travelling along the road being relaxedFour places joined by one-way roads with costs; the road from b to a costs −4. The number on a place is d, its cheapest total from s found so far. Bellman-Ford relaxes every road in list order, V − 1 = 3 times: a token carries d[u] + w along the road, and a cheaper total replaces d[v]. One more pass that still finds a cheaper total proves a negative cycle.

The problem

  1. 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.

Relaxing in rounds

Proof and checks

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.