Bellman-Ford and Floyd-Warshall
How Bellman-Ford finds shortest paths with negative edge costs and detects negative cycles, how Floyd-Warshall finds all pairs, and what interviews ask.
On this page
Bellman-Ford finds the cheapest route from one start node to every other node in a weighted directed graph, and it works even when some edge costs are negative. It can also tell you that a negative cycle exists, which is a loop whose total cost is below zero. Floyd-Warshall solves a different problem: it finds the cheapest route between every pair of nodes, also with negative costs allowed. You reach for these two when Dijkstra's algorithm cannot be used because of a negative cost.
Dijkstra finalises the closest unsettled node at each step, and that is only safe when no later edge can make a route cheaper. A negative edge breaks that assumption. Suppose S→A costs 1, S→B costs 2, B→A costs −4 and A→C costs 3. Dijkstra settles A at distance 1 and gives C a distance of 4, and only afterwards does it see that S→B→A costs −2, so the real distance to C is 1.
How Bellman-Ford works
Bellman-Ford does not choose a clever order. In each round it goes through every edge once, and for each edge from u to v it checks whether dist[u] + cost is smaller than dist[v]. If it is, it lowers dist[v]. This check is called relaxing an edge. The start node begins at distance 0 and every other node at infinity.
Each round extends the cheapest routes by one more edge, so after round k every node has the cost of its cheapest route that uses at most k edges. When there is no negative cycle, a cheapest route never visits a node twice, so it has at most V − 1 edges, and V − 1 rounds are enough.
The example below uses four depots S, A, B and C with five one-way legs. The leg from B to A has cost −4.
dist[start] = 0, all others ∞repeat V − 1 times: for each edge (u, v, cost): if dist[u] + cost < dist[v]: dist[v] = dist[u] + costfor each edge: if it still improves → negative cycle- edges, in this order0A→C 31C→S 12B→A −43S→A 14S→B 2
- round
- 0
1Distance S is 0 and every other depot starts at infinity. Each round checks the five edges in the order shown.
- edges, in this order0A→C 31C→S 12B→A −43S→A 14S→B 2
- round
- 1
2In round 1, the edges A→C, C→S and B→A all start at a depot whose distance is still infinity, so none of them changes anything.
- edges, in this order0A→C 31C→S 12B→A −43S→A 14S→B 2
- round
- 1
3The edge S→A gives 0 + 1 = 1, so the distance of A becomes 1.
- edges, in this order0A→C 31C→S 12B→A −43S→A 14S→B 2
- round
- 1
4The edge S→B gives 0 + 2 = 2, so the distance of B becomes 2. Round 1 is finished, and every route of one edge is now counted.
- edges, in this order0A→C 31C→S 12B→A −43S→A 14S→B 2
- round
- 2
5In round 2, the edge A→C gives 1 + 3 = 4, so the distance of C becomes 4. The edge C→S would give 4 + 1 = 5, which is worse than 0, so S is unchanged.
- edges, in this order0A→C 31C→S 12B→A −43S→A 14S→B 2
- round
- 2
6The edge B→A gives 2 + (−4) = −2, which is better than 1, so the distance of A drops to −2. This is the case where Dijkstra would already have finalised A.
- edges, in this order0A→C 31C→S 12B→A −43S→A 14S→B 2
- round
- 2
7The edges S→A and S→B improve nothing. C still holds 4, which was computed from the old value of A.
- edges, in this order0A→C 31C→S 12B→A −43S→A 14S→B 2
- round
- 3
8In round 3, the edge A→C gives −2 + 3 = 1, which is better than 4, so the distance of C becomes 1.
- edges, in this order0A→C 31C→S 12B→A −43S→A 14S→B 2
- round
- 3
9The remaining four edges change nothing. Round 3 is round V − 1, so every distance is now final.
- edges, in this order0A→C 31C→S 12B→A −43S→A 14S→B 2
- edge checks
- 20
10The extra check pass finds no edge that still improves a distance, so there is no negative cycle. The distances from S are A = −2, B = 2 and C = 1, found with 3 rounds of 5 edges plus the 5 edges of the check pass, which is 20 checks.
The order in which the edges are listed changes how many rounds are needed, but not the final answer. The code below stops early when a round changes nothing, and it finishes with one extra pass over the edges to detect a negative cycle.
// edges: list of [from, to, cost], one-way. nodes: list of names.
function bellmanFord(nodes, edges, start) {
const dist = {};
for (const node of nodes) dist[node] = Infinity;
dist[start] = 0;
for (let round = 1; round < nodes.length; round++) { // V - 1 rounds
let changed = false;
for (const [u, v, cost] of edges) {
if (dist[u] + cost < dist[v]) {
dist[v] = dist[u] + cost;
changed = true;
}
}
if (!changed) break; // nothing moved: every distance is final
}
for (const [u, v, cost] of edges) {
if (dist[u] + cost < dist[v]) return null; // still improving: negative cycle
}
return dist;
}
// bellmanFord(["S", "A", "B", "C"], edges, "S") → { S: 0, A: -2, B: 2, C: 1 }import math
# edges: list of (from, to, cost), one-way. nodes: list of names.
def bellman_ford(nodes, edges, start):
dist = {node: math.inf for node in nodes}
dist[start] = 0
for _ in range(len(nodes) - 1): # V - 1 rounds
changed = False
for u, v, cost in edges:
if dist[u] + cost < dist[v]:
dist[v] = dist[u] + cost
changed = True
if not changed:
break # nothing moved: every distance is final
for u, v, cost in edges:
if dist[u] + cost < dist[v]:
return None # still improving: negative cycle
return dist
# bellman_ford(["S", "A", "B", "C"], edges, "S") → {'S': 0, 'A': -2, 'B': 2, 'C': 1}At most V − 1 rounds run, and each round looks at every edge.
Negative cycles
A negative cycle makes the problem unsolvable, because every extra lap around the loop lowers the cost again. In the example, adding a leg C→B with cost −2 creates the loop B→A→C→B with total cost −4 + 3 − 2 = −3.
If there is no negative cycle, no distance changes after round V − 1. So Bellman-Ford runs one more pass, and if any edge can still lower a distance, a negative cycle is reachable from the start. The function then returns null instead of wrong numbers. A negative cycle that the start node cannot reach is never touched, because its nodes stay at infinity.
How Floyd-Warshall works
Floyd-Warshall keeps a table with the cheapest known cost for every pair of nodes. It starts with the direct edges and then allows the nodes as stopovers one at a time. When node k becomes allowed, each pair i, j is compared against the route that goes from i to k and then from k to j, and the smaller cost is kept.
This is correct because the best route from i to j that may use stopovers up to k either avoids k, in which case it is already in the table, or passes through k once, in which case it is the best i to k route plus the best k to j route, and both of those are also in the table.
dist = direct costs (0 on the diagonal, ∞ if no leg)for k in nodes: # allow k as a stopover for i in nodes: for j in nodes: dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])- dist (row = from, column = to)
S A B C S 0 1 2 ∞ A ∞ 0 ∞ 3 B ∞ −4 0 ∞ C 1 ∞ ∞ 0 - stopovers allowed
- none
1The table starts with the direct legs only. The diagonal is 0 because staying put is free, and a cell is infinity where there is no direct leg.
- dist (row = from, column = to)
S A B C S 0 1 2 ∞ A ∞ 0 ∞ 3 B ∞ −4 0 ∞ C 1 2 3 0 - k
- S
- stopovers allowed
- S
- cells improved
- 2
2Allow S as a stopover. Only C has a leg into S, so only row C improves: C→S→A costs 1 + 1 = 2 and C→S→B costs 1 + 2 = 3.
- dist (row = from, column = to)
S A B C S 0 1 2 4 A ∞ 0 ∞ 3 B ∞ −4 0 −1 C 1 2 3 0 - k
- A
- stopovers allowed
- S, A
- cells improved
- 2
3Allow A as well. S→A→C costs 1 + 3 = 4, and B→A→C costs −4 + 3 = −1.
- dist (row = from, column = to)
S A B C S 0 −2 2 1 A ∞ 0 ∞ 3 B ∞ −4 0 −1 C 1 −1 3 0 - k
- B
- stopovers allowed
- S, A, B
- cells improved
- 3
4Allow B as well. S→B→A costs 2 − 4 = −2, which beats 1. S→B→C costs 2 + (−1) = 1, which beats 4 and reuses the entry for B→A→C. C→B→A costs 3 − 4 = −1, which beats 2.
- dist (row = from, column = to)
S A B C S 0 −2 2 1 A 4 0 6 3 B 0 −4 0 −1 C 1 −1 3 0 - k
- C
- stopovers allowed
- S, A, B, C
- cells improved
- 3
5Allow C as well. A→C→S costs 3 + 1 = 4, A→C→B costs 3 + 3 = 6, and B→C→S costs −1 + 1 = 0.
- dist (row = from, column = to)
S A B C S 0 −2 2 1 A 4 0 6 3 B 0 −4 0 −1 C 1 −1 3 0 - checks
- 64
6The table is complete. Row S matches the Bellman-Ford result of −2, 2 and 1, and the diagonal is all 0, so there is no negative cycle. The three nested loops made 4 × 4 × 4 = 64 checks and produced all 16 answers.
// Places are numbered 0..n-1. edges: list of [from, to, cost], one-way.
function floydWarshall(n, edges) {
const dist = Array.from({ length: n }, (_, i) =>
Array.from({ length: n }, (_, j) => (i === j ? 0 : Infinity)));
for (const [u, v, cost] of edges) dist[u][v] = Math.min(dist[u][v], cost);
for (let k = 0; k < n; k++) { // allow k as a stopover
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
if (dist[i][k] + dist[k][j] < dist[i][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}
return dist; // a negative dist[i][i] means i is on a negative cycle
}import math
# Places are numbered 0..n-1. edges: list of (from, to, cost), one-way.
def floyd_warshall(n, edges):
dist = [[0 if i == j else math.inf for j in range(n)] for i in range(n)]
for u, v, cost in edges:
dist[u][v] = min(dist[u][v], cost)
for k in range(n): # allow k as a stopover
for i in range(n):
for j in range(n):
if dist[i][k] + dist[k][j] < dist[i][j]:
dist[i][j] = dist[i][k] + dist[k][j]
return dist # a negative dist[i][i] means i is on a negative cycleThree nested loops each run over all V nodes, and the table has V × V cells.
Variants and when each algorithm applies
Choosing between BFS, Dijkstra, Bellman-Ford and Floyd-Warshall
Use breadth-first search when every edge costs the same, because it is the fastest. Use Dijkstra when costs differ but none is negative. Use Bellman-Ford when there is one start node and some costs are negative. Use Floyd-Warshall when you need the answer for every pair of nodes, which is practical only for a few hundred nodes because of the V³ time.
| Approach | Time | Space | Why |
|---|---|---|---|
| Bellman-Ford | O(V × E) | O(V) | It runs at most V − 1 rounds, and each round looks at every edge. |
| Floyd-Warshall | O(V³) | O(V²) | It has three nested loops over the places and stores one table of V × V costs. |
| Dijkstra, for comparison | O((V + E) log V) | O(V + E) | It is faster, but it only works when no cost is negative. |
Negative cycles in Floyd-Warshall
Floyd-Warshall has no separate check pass. After it finishes, a node i lies on a negative cycle if dist[i][i] is below 0. When a negative cycle exists, the other entries that route through it are not reliable either, so a problem that allows negative cycles needs this check before the table is used.
Bellman-Ford with a limit on the number of edges
Because round k covers routes of at most k edges, Bellman-Ford can answer "the cheapest route using at most k edges", as in problems about flights with at most k stops. Run exactly the allowed number of rounds, and in each round read the distances from a copy made at the start of the round. Without the copy, an update made earlier in the same round can be used again in that round, and a route ends up with more edges than allowed.
When these algorithms do not apply
If the graph is undirected, a negative edge cannot be used, because an undirected edge of cost −4 is the same as two directed edges of cost −4, and going across it and back is a negative cycle of cost −8. If a problem asks for the cheapest route that is allowed to repeat nodes and a negative cycle is reachable, the answer is minus infinity and not a number. Finding the cheapest simple path in a graph with negative cycles is a much harder problem that neither algorithm solves.
Pitfalls
In the interview
Look for a weighted directed graph where some costs can be negative, such as refunds, discounts, profits or exchange rates. The words "cheapest", "at most k stops", "detect an arbitrage" or "is there a loop that gains money" point to Bellman-Ford. A request for the shortest distance between all pairs of a small graph, such as a distance matrix or the transitive closure, points to Floyd-Warshall.
Questions to expect:
- "Why does Dijkstra fail with a negative edge?" Dijkstra assumes that once a node is the closest unsettled one, no other route can reach it more cheaply. A negative edge later in the graph can make a longer route cheaper, but the node is already settled and is never updated.
- "Why are V − 1 rounds enough?" Without a negative cycle, a cheapest route never repeats a node, so it has at most V − 1 edges. After round
kall cheapest routes of up tokedges are correct, so after V − 1 rounds all of them are. - "How do you detect a negative cycle?" Run one more round after V − 1 rounds. If any edge still lowers a distance, then a negative cycle is reachable from the start. In Floyd-Warshall you check whether any
dist[i][i]is negative. - "How would you speed up Bellman-Ford?" Stop as soon as a round changes nothing, which the code above already does. A queue-based version that only re-examines the neighbours of nodes whose distance just changed is often much faster in practice, but its worst case is still O(V × E).
- "How do you get the actual path and not only the cost?" In Bellman-Ford, store the previous node each time a distance is lowered, then walk back from the target. In Floyd-Warshall, store for each pair the first or last node of the best route and update it whenever the table entry improves.
- "How do you find all-pairs shortest paths on a large sparse graph with negative edges?" Johnson's algorithm runs Bellman-Ford once to compute a reweighting that makes every edge cost non-negative without changing which routes are cheapest, and then runs Dijkstra from every node. This is faster than O(V³) when the graph is sparse.
- "When would you use Floyd-Warshall instead of running Dijkstra from every node?" Floyd-Warshall is shorter to write and handles negative costs, so it is a good choice for a small or dense graph. For a large sparse graph with no negative costs, running Dijkstra once per node is faster.
Check your understanding
A graph has 6 places and no negative cycle. At most how many rounds does Bellman-Ford need?
After V − 1 rounds, the check pass finds an edge that still lowers a distance. What does that mean?
You need the cheapest cost between every pair among 200 warehouses, and all costs are positive. Which fits best?
What to practise next
A related graph problem is connecting all nodes as cheaply as possible, which is covered in Minimum Spanning Trees and uses Union-Find.