Skip to content
StackDecode
GraphsAnimated

Bellman–Ford Algorithm

Relax every edge V−1 times; one more pass detects negative cycles.

Time

O(V · E)

Extra space

O(V)

Use it for

Graphs with negative weights.

How it works

  1. Set the start distance to 0 and every other to ∞.
  2. Repeat V − 1 times: look at every edge (u → v, w) and relax it: if dist[u] + w is smaller than dist[v], update dist[v].
  3. A shortest path has at most V − 1 edges, so after V − 1 rounds all distances are final.
  4. One extra round that still improves something proves a negative cycle. Works with negative weights, unlike Dijkstra. O(V · E).

Watch it run

Loading animation…