Bellman-Ford & Floyd-Warshall
Handle negative edge weights, detect negative cycles and compute all-pairs shortest paths.
By Invicly Tech, , in Data Structures & Algorithms. About 12 minutes to read.
In short
Bellman-Ford relaxes every edge V-1 times, which is enough for shortest paths with up to V-1 edges, and it works with negative weights. A further pass that still improves a distance proves a negative cycle. Floyd-Warshall computes shortest paths between all pairs with a triple loop.
Explained simply
Sometimes an edge has a negative weight. Think of a delivery route where one stop pays you a bonus, or a currency trade that gains money. Dijkstra breaks on such graphs. Bellman-Ford is slower, but it still gives the right answer.
Bellman-Ford is almost too simple. It looks at every edge in the graph and relaxes it: if going through this edge gives a shorter distance, it writes the new value down. One full pass over all edges is called a round. It repeats V - 1 rounds, where V is the number of vertices.
Why V - 1? A shortest path that does not repeat vertices has at most V - 1 edges. Each round fixes at least one more edge of every shortest path. So after V - 1 rounds, every distance is correct.
There is a bonus. If one more round still makes something shorter, the graph has a negative cycle: a loop whose total weight is below zero. You could go around it forever and keep getting "shorter", so there is no real shortest path. Floyd-Warshall, the other algorithm here, finds shortest paths between all pairs of vertices at once.
Press Play on a diagram to walk through it one step at a time.
- Non-negative weights only
- O((V + E) log V)
- Single source
- Handles negative weights
- Detects negative cycles
- O(V x E)
- Single source
- All pairs
- O(V^3) time, O(V^2) space
- Handles negative edges
- 1Start
dist = [0, inf, inf, inf]
- 2Round 1
0 to 1 and 0 to 2 relax: [0, 4, 5, inf]
- 3Round 2
3 = 7, then 1 = 5 - 2 = 3: [0, 3, 5, 7]
- 4Round 3
3 = 3 + 3 = 6: [0, 3, 5, 6]
- 5Check pass
No change, so no negative cycle.
In depth
What one round really guarantees
Claim: after round k, dist[v] is at most the cost of the cheapest path from the source to v that uses at most k edges. Proof by induction: the cheapest path with k edges is a cheapest path with k - 1 edges plus one last edge (u, v). After round k - 1, dist[u] is good enough, and round k relaxes (u, v).
Because updates happen in place, a round can do better than this and fix several edges of one path at once, depending on the edge order. That is why a common speed-up works: if a round changes nothing, every later round will change nothing too, so stop. On many real graphs this ends after a few rounds, and the best case is O(E).
- Worst case: O(V x E) time, O(V) extra space
- Early exit when a round makes no change
- Edge order affects speed, never correctness
Finding a negative cycle, not just detecting it
Run V rounds instead of V - 1 and remember parent[v] on every relaxation. If round V still relaxes some vertex x, x is on a negative cycle or reachable from one. Walk parent pointers back from x V times: you are now guaranteed to stand on the cycle itself. Then keep following parents until you return to the same vertex, and you have the whole cycle.
To check the whole graph rather than only what one source can reach, start with dist = 0 for every vertex. That acts like an invisible extra source with a 0-weight edge to everyone.
- 1Run V rounds
Track parent[v] on each relaxation.
- 2Round V relaxes x?
No: no negative cycle.
- 3Step back V times
x = parent[x], now on the cycle.
- 4Follow parents
Until you return to x.
- 5Reverse
That list is the cycle in edge order.
Hop limits: cheapest path with at most k stops
Some problems cap the number of edges, such as "cheapest flight with at most k stops". k stops means k + 1 flights, so you run exactly k + 1 rounds. But the in-place speed-up from above is now a bug: within one round, a distance updated early could be used again later in the same round, letting a path sneak in an extra edge.
The fix is to read from the old array and write to a copy: new = dist[:] at the start of each round, relax using dist[u], store into new[v], then replace dist with new. Now round r really means "at most r edges". The cost is O(k x E) time and O(V) space.
- k stops = k + 1 edges = k + 1 rounds
- Copy the array each round
- Dijkstra on (city, stops) states also works
Floyd-Warshall: all pairs in a triple loop
Floyd-Warshall keeps a V x V matrix d, starting from edge weights, 0 on the diagonal and infinity elsewhere. It then allows vertex k as an intermediate stop, for k = 0, 1, ..., V - 1, updating d[i][j] = min(d[i][j], d[i][k] + d[k][j]). After phase k, d[i][j] is the shortest path whose intermediate vertices all come from 0..k.
Time is exactly V^3 inner steps, O(V^3), and space O(V^2). In Python, V = 200 is 8 million steps (fine); V = 1,000 is 10^9 steps (far too slow). After it finishes, any d[i][i] < 0 means vertex i lies on a negative cycle. To rebuild paths, keep a next matrix and update it whenever d[i][j] improves.
Where it shows up in practice
Distance-vector routing protocols such as RIP are a distributed Bellman-Ford: each router tells its neighbours its current distances, and they relax. RIP caps paths at 15 hops and treats 16 as unreachable, to limit the "count to infinity" problem.
Currency arbitrage is a classic negative-cycle search. Give the edge from currency i to j the weight -log(rate). Multiplying rates becomes adding logs, so a loop of trades that ends with more money than it started has a negative total weight.
A queue-based version called SPFA only relaxes edges out of vertices that changed. It is often faster in practice, but its worst case is still O(V x E).
Learn it in 4 short steps
About 45m each. Track them with a timer in your plan.
- 1Relax all edges V-1 times~45m
- 2Detect negative cycles~45m
- 3Solve limited-stops shortest paths~45m
- 4Implement Floyd-Warshall for all pairs~45m
Key points
- After k rounds, distances are correct for paths of at most k edges.
- That property solves cheapest flights within k stops.
- Floyd-Warshall's loop order matters: the intermediate vertex k is the outer loop.
- Shortest paths are undefined when a negative cycle is reachable.
Key terms
Tap a card to flip it. 0/3 known
Examples
def bellman_ford(n, edges, src): # O(V * E)
dist = [float('inf')] * n
dist[src] = 0
for _ in range(n - 1):
for u, v, w in edges:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
for u, v, w in edges:
if dist[u] + w < dist[v]:
return None # negative cycle
return dist
print(bellman_ford(3, [(0, 1, 4), (0, 2, 5), (2, 1, -2)], 0)) # [0, 3, 5]Cheapest flights within k stops
Flights: 0 to 1 costs 100, 1 to 2 costs 100, 2 to 0 costs 100, 1 to 3 costs 600, 2 to 3 costs 200. From 0 to 3 with at most 1 stop: round 1 reaches 1 for 100; round 2 reaches 2 for 200 and 3 for 700. The answer is 700. With 2 stops, round 3 finds 0, 1, 2, 3 for 400. The copied array is what stops round 2 from chaining 0 to 1 to 2 in a single round.
def cheapest(n, flights, src, dst, k): # O(k * E)
INF = float("inf")
dist = [INF] * n
dist[src] = 0
for _ in range(k + 1): # k stops = k + 1 edges
new = dist[:] # read old, write new
for u, v, w in flights:
if dist[u] + w < new[v]:
new[v] = dist[u] + w
dist = new
return -1 if dist[dst] == INF else dist[dst]
flights = [[0, 1, 100], [1, 2, 100], [2, 0, 100], [1, 3, 600], [2, 3, 200]]
print(cheapest(4, flights, 0, 3, 1)) # 700
print(cheapest(4, flights, 0, 3, 2)) # 400Spotting currency arbitrage
Rates: 1 USD buys 0.9 EUR, 1 EUR buys 0.9 GBP, 1 GBP buys 1.3 USD. Trading around the loop turns 1 USD into 0.9 x 0.9 x 1.3 = 1.053 USD, free money. Step 1: weight each edge -log(rate), so a profitable loop has a negative sum. Step 2: start every distance at 0 so all currencies are checked. Step 3: run V - 1 rounds, then one more check pass. A small tolerance avoids false alarms from floating-point rounding.
import math
def has_arbitrage(rates): # rates[i][j]: 1 unit of i buys this much j
n = len(rates)
edges = [(i, j, -math.log(rates[i][j]))
for i in range(n) for j in range(n) if i != j]
dist = [0.0] * n # every currency is a start
for _ in range(n - 1):
for u, v, w in edges:
if dist[u] + w < dist[v] - 1e-12:
dist[v] = dist[u] + w
return any(dist[u] + w < dist[v] - 1e-12 for u, v, w in edges)
rates = [[1, 0.9, 0.8], [1.1, 1, 0.9], [1.3, 1.1, 1]] # USD, EUR, GBP
print(has_arbitrage(rates)) # TrueQuick reference
- Bellman-Ford: V - 1 rounds over all E edges, O(V x E) time, O(V) space
- An extra round that still relaxes an edge means a reachable negative cycle
- Stop early when a whole round changes nothing
- At most k stops: k + 1 rounds, and copy dist at the start of each round
- Floyd-Warshall: for k, for i, for j, with k outermost; O(V^3) time, O(V^2) space
- After Floyd-Warshall, d[i][i] < 0 means i is on a negative cycle
- Arbitrage: weight = -log(rate), then look for a negative cycle
- An undirected negative edge is already a negative cycle (go back and forth)
Common mistakes
- Putting k as the inner loop in Floyd-Warshall.
- Updating in place when solving the k-stops variant; copy distances each round.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Add an early exit to Bellman-Ford: stop as soon as a whole round makes no change. Keep the negative-cycle check working.
- Exercise 2medium
Write floyd_warshall(n, edges) that returns the all-pairs distance matrix, or None if any negative cycle exists. edges are (u, v, w) directed.
- Exercise 3hard
Write find_neg_cycle(n, edges) that returns the list of vertices on some negative cycle (in edge order), or None.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- When should I use Bellman-Ford instead of Dijkstra?
- Only when edges can be negative, when you need a negative-cycle check, or when the number of edges in the path is limited. Otherwise Dijkstra is much faster.
- Does Bellman-Ford work on undirected graphs?
- Only if all weights are non-negative. An undirected edge with a negative weight is a two-edge negative cycle, because you can walk it back and forth forever.
- Should I run Dijkstra V times or Floyd-Warshall for all pairs?
- With non-negative weights on a sparse graph, V runs of Dijkstra cost O(V (V + E) log V), which beats O(V^3). Floyd-Warshall is simpler, handles negative edges, and suits small dense graphs.
- What does the shortest path mean if there is a negative cycle?
- For vertices the cycle can reach, it is undefined: you can loop and make the cost as low as you like. Algorithms report the cycle or mark those distances as minus infinity.