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
- Set the start distance to 0 and every other to ∞.
- 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].
- A shortest path has at most V − 1 edges, so after V − 1 rounds all distances are final.
- 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…