Bellman-Ford & Floyd-Warshall
When links can be negative, or you need the distance between every pair, two slower algorithms take over: Bellman-Ford from one source, and Floyd-Warshall for all pairs.
With negative links, relax everything again and again
Dijkstra's algorithm settles a node once and never looks back, which is only safe when no link subtracts. With negative weights (a refund, a downhill segment, a profit), take the slow, safe road: relax every link, then do it again, until nothing changes.
That is Bellman-Ford. After round r, every node whose shortest route uses at most r links has its final distance. A shortest route never repeats a node, so it has at most n − 1 links, and n − 1 rounds are always enough.
Unless a negative cycle is reachable: a loop whose weights add up to less than zero. Going round it once more always lowers the total, so no shortest route exists at all. Bellman-Ford detects it with one extra pass: if any link can still be relaxed after n − 1 rounds, there is a negative cycle.
The rule
Bellman-Ford relaxes every link n − 1 times, which is enough for any shortest route, in O(n × m). If a link still improves on an extra pass, the graph has a negative cycle and shortest distances are undefined.
Each round lets routes grow by one more link
Here the links are listed in an unhelpful order, so the first round only gets one link away from the start. Watch the negative link 2 → 3 improve node 3 in round 2, and that improvement reach node 4 in round 3.
Dijkstra's algorithm would settle node 3 at 5, through node 1, before it even took node 2 at 6. The cheaper route 0 → 2 → 3, at 6 − 4 = 2, turns up only after node 3 is settled, too late for the nodes it already reached through node 3.
Count the rounds, and you limit the number of links
Because round r covers routes of up to r links, Bellman-Ford can also answer "cheapest with at most k stops": run k + 1 rounds. One detail matters. Within a round, a price set earlier in the same round must not be extended again, or a route could gain two flights at once. So each round reads from a copy of the previous round's prices.
Floyd-Warshall fills a table of every pair
When you need the distance between every pair of nodes, Floyd-Warshall builds an n × n table. It starts with the direct links, then lets each node in turn act as a stop in the middle: for node k, every pair i, j checks whether i → k → j beats the table's current i → j. After every node has had its turn, the table holds every shortest distance.
This is dynamic programming: after round k, each entry is the shortest route that only stops at nodes 0 to k on the way. The order of the loops matters: k must be the outer one.
Negative links are fine here too, and a negative cycle shows up as a negative number on the diagonal: a node that can return to itself for less than nothing.
Pick the cheapest algorithm the weights allow
Problem | Algorithm | Cost |
|---|---|---|
All links weigh the same | BFS | O(n + m) |
One source, no negative weights | Dijkstra's algorithm | O((n + m) log n) |
One source, negative weights, or a limit on links | Bellman-Ford | O(n × m) |
Every pair, n up to a few hundred | Floyd-Warshall | O(n³) |
Floyd-Warshall's three short loops make it the easiest to write when n is small. For every pair in a large sparse graph with no negative weights, running Dijkstra's algorithm from each node is faster.
3 questions
Remember this
- Bellman-Ford relaxes every link n − 1 times and handles negative weights: O(n × m).
- An improvement on an extra pass reveals a negative cycle, where no shortest route exists.
- Round r covers routes of up to r links, which also solves "at most k stops".
- Floyd-Warshall fills an all-pairs table by letting each node in turn be a stop: O(n³).
Now solve some yourself
Only this topic 0 of 9 solved
- MediumSignal delay by repeated relaxation
- MediumShortest routes between any two cities
- MediumRoads no shortest route uses
- MediumCheapest way to turn one string into another, letter by letter
- MediumCount house pairs at each distance on a street with a shortcut
- MediumThe route most likely to succeed
- HardA graph that answers shortest-route queries
- HardHighest score on a route, or say it is unbounded
- HardFind a negative cycle
Mixed with topics you have practiced 0 unlocked
4 more once you have practiced Topological sort, Hash tables & maps, Dynamic programming: basics, Dynamic programming: classic families, Tries. Play one of its examples to the end and solve one of its problems to unlock them.
Problems open on their own sites (LeetCode, Codeforces, CodeChef, AtCoder, CSES) in a new tab. Tick Solved when you get it accepted there; your ticks decide which mixed problems open next.
Next