Advanced 12 min

Bellman–Ford and negative edges

Bellman–Ford finds shortest paths by repeatedly checking whether any edge improves a known distance.

How it works

Start with distance 0 at the source and unknown distance elsewhere. A relaxation asks whether going through one already reachable vertex gives a better path to its neighbor. You may discover a new route on a later pass, even when its first edges appear late in the edge list.

Walk through an example

An edge A → B of weight -2 can turn a known distance of 5 to A into a distance of 3 to B. Repeat this relaxation across all edges up to V − 1 passes for V vertices.

What to watch for

Only relax from a vertex with a known finite distance. A further improvement after those passes indicates a reachable negative-weight cycle.

Code example

def relax(dist, start, end, weight):
    if dist[start] is not None:
        candidate = dist[start] + weight
        if dist[end] is None or candidate < dist[end]:
            dist[end] = candidate

Check your understanding

What distance should replace 8?

See the example and explanation
Worked example
Given Distance to A is 5. A → B has weight -2. Current distance to B is 8.
Answer 3

Traveling via A costs 5 + (-2) = 3, which is smaller than 8.

Open practice problem
Next lesson0/1 knapsack