Quick reference
The Floyd-Warshall algorithm finds the shortest paths between every pair of nodes in a weighted graph. It keeps a table of distances between every two nodes, and for each node k in turn, it checks whether stopping at k along the way gives a shorter path from i to j. It handles negative edge weights, detects negative cycles, and runs in O(V³) time, where V is the number of nodes.
When to use it:
- You need the shortest distance between every pair of nodes (or lots of different pairs), and the graph is small or dense.
- Some edge weights are negative, or you need to know whether the graph has a negative cycle.
- You want short, simple code: it's three nested loops.
How it works:
-
Fill a V \times V table:
dist[i][j]is the weight of the edge from i to j, 0 when i = j, and infinity when there's no edge. -
For each node k (the outer loop), for each
pair i, j: set
dist[i][j]todist[i][k] + dist[k][j]if that's smaller. -
If any
dist[i][i]ends up below 0, the graph has a negative cycle.
Cost:
- O(V³) time and O(V²) space, no matter how many edges there are.
How the Floyd-Warshall Algorithm Works
Floyd-Warshall is dynamic programming. Instead of searching outward from one node, it lets paths use more and more nodes as stops in between:
- First, paths can't stop anywhere. The only routes are the edges themselves.
- Then paths can stop at node 0.
- Then at nodes 0 and 1.
- And so on, until paths can stop anywhere. At that point, the table holds the real shortest distances.
When we add node k to the allowed stops, the shortest path from i to j either skips k or goes through it:
-
It skips k. Then it's the
best path we already had:
dist[i][j]. -
It goes through k. Then it's
the best path from i to k
followed by the best path from k to
j, and neither of those halves needs to stop
at k again. That's
dist[i][k] + dist[k][j].
So we keep whichever is smaller:
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
(Why would a shortest path visit k only once? Visiting it twice means looping from k back to k. As long as there's no negative cycle, cutting out that loop doesn't make the path any longer.)
We don't even need a new table for each k. While
we're working on node k, dist[i][k]
and dist[k][j] don't change, since going from
i to k "by way of
k" just adds dist[k][k], which is 0.
So we can update one table in place:
Floyd-Warshall Example, Step by Step
Here's a directed graph with 4 nodes and 6 edges. One edge has a negative weight, but there's no negative cycle.
| Edge | Weight |
|---|---|
| 0 → 1 | 7 |
| 0 → 2 | 1 |
| 1 → 3 | 3 |
| 2 → 0 | 8 |
| 2 → 3 | −3 |
| 3 → 1 | 4 |
Start (no stops allowed): each row is a starting node and each column is a destination. Every entry is just the edge's weight, 0 on the diagonal, or ∞ if there's no edge.
| From \ To | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| 0 | 0 | 7 | 1 | ∞ |
| 1 | ∞ | 0 | ∞ | 3 |
| 2 | 8 | ∞ | 0 | −3 |
| 3 | ∞ | 4 | ∞ | 0 |
k = 0 (paths can stop at node 0): only node 2 has an edge into node 0, so only routes from node 2 can improve. 2 → 0 → 1 costs 8 + 7 = 15, which beats ∞.
| From \ To | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| 0 | 0 | 7 | 1 | ∞ |
| 1 | ∞ | 0 | ∞ | 3 |
| 2 | 8 | 15 | 0 | −3 |
| 3 | ∞ | 4 | ∞ | 0 |
k = 1 (paths can also stop at node 1): 0 → 1 → 3 costs 7 + 3 = 10, which beats ∞. (Going from 2 to 3 through node 1 would cost 15 + 3 = 18, which doesn't beat −3.)
| From \ To | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| 0 | 0 | 7 | 1 | 10 |
| 1 | ∞ | 0 | ∞ | 3 |
| 2 | 8 | 15 | 0 | −3 |
| 3 | ∞ | 4 | ∞ | 0 |
k = 2 (paths can also stop at node 2): 0 → 2 → 3 costs 1 + (−3) = −2, which beats the 10 we just found. A negative distance is fine. It's only a problem if a node can get back to itself for less than 0.
| From \ To | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| 0 | 0 | 7 | 1 | −2 |
| 1 | ∞ | 0 | ∞ | 3 |
| 2 | 8 | 15 | 0 | −3 |
| 3 | ∞ | 4 | ∞ | 0 |
k = 3 (paths can stop anywhere): two routes improve by going through node 3 and then taking the edge 3 → 1:
-
From 0 to 1:
dist[0][3] + dist[3][1]= −2 + 4 = 2, which beats 7. The path is 0 → 2 → 3 → 1. -
From 2 to 1:
dist[2][3] + dist[3][1]= −3 + 4 = 1, which beats 15. The path is 2 → 3 → 1.
| From \ To | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| 0 | 0 | 2 | 1 | −2 |
| 1 | ∞ | 0 | ∞ | 3 |
| 2 | 8 | 1 | 0 | −3 |
| 3 | ∞ | 4 | ∞ | 0 |
That's the answer: the shortest distance between every pair of nodes. The ∞ entries that are left are real: nodes 1 and 3 have no way to get to nodes 0 or 2. And no number on the diagonal is negative, so there's no negative cycle.
Notice that the distance from 0 to 3 improved twice (∞ to 10 to −2) as more stops were allowed, and the final distance from 0 to 1 builds on it.
Why k Has to Be the Outer Loop
It's tempting to write the loops in the order i, j, k: "for each pair, try every node in between." That's the most common Floyd-Warshall bug, and it gives wrong answers.
With k on the outside, the whole table is finished for "stops at nodes 0 through k" before we move on to k + 1. Each round builds on a complete round before it.
With k on the inside, we settle
dist[i][j] once and never come back to it, using
whatever dist[i][k] and dist[k][j] happen
to hold at that moment. Lots of those haven't been improved yet.
In our example, the i, j,
k order gets the distance from 0 to 1 wrong. When
it fills in dist[0][1], it tries each stop:
-
Through node 2:
dist[0][2] + dist[2][1]= 1 + ∞, because row 2 hasn't been filled in yet. -
Through node 3:
dist[0][3] + dist[3][1]= ∞ + 4, becausedist[0][3]comes later in row 0, so it's still ∞.
So it keeps the direct edge, 7, and never looks at
dist[0][1] again. The right answer is 2.
The order of the two inner loops doesn't matter. k, i, j and k, j, i both work. Just keep k outside both of them.
Floyd-Warshall Algorithm Code
Nodes are numbered 0 to V - 1, and the graph is an array of edges, each with a starting node, an ending node, and a weight. This is the example from above:
Some notes on the code:
- Infinity. In Python and JavaScript, infinity plus a number is still infinity, so pairs with no path take care of themselves. Java and C++ ints don't have an infinity, so we use the biggest int as a stand-in and skip any route through k where either half is missing. Adding to it would overflow.
- We check for a negative cycle after every row, not just once at the end. With a negative cycle, the numbers can get more negative very quickly. On a 16-node graph where every edge has a weight of −1, running all the rounds pushes some distances past −300 billion, way past what a 32-bit int can hold. Stopping as soon as a diagonal entry drops below 0 keeps the numbers from running away.
- Parallel edges. If the input has two edges from the same node to the same node, keep the shorter one instead of whichever comes last.
- Undirected graphs. Add each edge in both directions. An undirected edge with a negative weight is a negative cycle all by itself, since you can go back and forth across it.
Negative Edges and Negative Cycles
Negative edge weights are fine. The argument for why Floyd-Warshall works only needs shortest paths that don't loop, and that's true as long as there's no negative cycle. Our example has a negative edge, and every distance came out right.
A negative cycle shows up on the diagonal.
dist[i][i] starts at 0, and it only drops below 0 if
node i can leave and come back for a total of less
than 0. And if the graph has a negative cycle, at least one node on
that cycle ends up with a negative dist[i][i]. So the
graph has a negative cycle exactly when some
dist[i][i] ends up below 0.
For example, add an edge from node 3 to node 2 with a weight of 2.
Now the loop 2 → 3 → 2 costs −3 + 2 = −1. When
k = 2, the algorithm finds that node 3 can go to
node 2 and back for dist[3][2] + dist[2][3] =
2 + (−3) = −1, so dist[3][3] drops to
−1 and the code reports a negative cycle.
Once there's a negative cycle, the rest of the table can't be trusted. Any pair whose path can detour around the cycle has no shortest path at all, because each trip around makes it cheaper.
Getting the Actual Paths
The table tells you how far it is from i to
j, but not which way to go. To get the paths,
keep a second V \times V table,
next[i][j]: the node right after i
on the shortest path from i to
j.
-
Start with
next[i][j] = jfor every edge, andnext[i][i] = i. -
Whenever going through k improves
dist[i][j], the new path from i to j starts out the same way as the path from i to k. So setnext[i][j] = next[i][k]. -
To read off a path, start at i and keep
jumping to
next[current][j]until you get to j.
Here's the finished next table for our example (a
dash means there's no path):
| From \ To | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| 0 | 0 | 2 | 2 | 2 |
| 1 | — | 1 | — | 3 |
| 2 | 0 | 3 | 2 | 3 |
| 3 | — | 1 | — | 3 |
For the path from 0 to 1: next[0][1] is 2,
next[2][1] is 3, and next[3][1] is 1. So
the path is 0 → 2 → 3 → 1, which costs
1 + (−3) + 4 = 2, matching dist[0][1].
Only read off paths when there's no negative cycle. With one, the jumps can go around the cycle forever.
Floyd-Warshall Time and Space Complexity
Time: O(V³). There are three nested loops over the V nodes, and each step does O(1) work. The number of edges doesn't matter: a graph with no edges takes just as long as one with an edge between every pair.
Space: O(V²) for
the distance table, plus another O(V²)
for the next table if you want paths. You need room
for the answer anyway: there are V^2 pairs.
Floyd-Warshall vs. running a single-source algorithm from every node
You can also get every pair's distance by running Dijkstra's algorithm or Bellman-Ford once from each node. Here's how that compares (E is the number of edges):
| Approach | Time | Negative edges? | Best for |
|---|---|---|---|
| Floyd-Warshall | O(V³) | Yes | Small or dense graphs, and short code |
| Dijkstra's from every node | O(V(V + E) log V) | No | Big, sparse graphs with no negative weights |
| Bellman-Ford from every node | O(V² · E) | Yes | Almost never: on a dense graph that's O(V⁴) |
| BFS from every node | O(V(V + E)) | No weights at all | Unweighted graphs |
The deciding factor is how many edges there are:
- In a sparse graph, where E is about the same as V, running Dijkstra's from every node takes O(V² log V), which beats Floyd-Warshall's O(V³).
- In a dense graph, where E is close to V^2, Dijkstra's from every node takes O(V³ log V), and Floyd-Warshall wins. It's also much less code.
- If you only need distances from a few start nodes, skip Floyd-Warshall and run Dijkstra's algorithm (or Bellman-Ford, if some weights are negative) from just those nodes.
For big, sparse graphs with negative edges, there's also Johnson's algorithm. It runs Bellman-Ford once to reweight the edges so none are negative (without changing which paths are shortest), then runs Dijkstra's from every node.
Dijkstra vs. Bellman-Ford vs. Floyd-Warshall
| Dijkstra's algorithm | Bellman-Ford | Floyd-Warshall | |
|---|---|---|---|
| Finds | Shortest paths from one start node | Shortest paths from one start node | Shortest paths between every pair of nodes |
| Negative edge weights? | No | Yes | Yes |
| Detects negative cycles? | No | Yes, if you can reach them from the start node | Yes: some dist[i][i] ends up below 0 |
| Time | O((V + E) log V) with a binary heap | O(V · E) | O(V³) |
| Extra space | O(V) | O(V) | O(V²) |
| Approach | Greedy: finalize the closest unfinished node, using a priority queue | Dynamic programming: relax every edge, V - 1 times | Dynamic programming: allow one more node as a stop in between, V times |
| Typical use | Maps, routing, and any graph where weights are never negative | Graphs with negative weights; finding negative cycles (like a loop of currency trades that makes money); limits on the number of edges | Small or dense graphs where you need the distance between every pair; checking which nodes can reach which |
For a full walkthrough of the single-source algorithm that handles negative weights, see the Bellman-Ford algorithm. For more on counting steps like these, see our big O notation guide.
Transitive Closure: Which Nodes Can Reach Which
Sometimes you don't care how far it is from i to j, just whether you can get there at all. That's called the transitive closure of the graph, and the same three loops find it. Use true and false instead of numbers: i can reach j if it already could, or if i can reach k and k can reach j. (This version is sometimes called Warshall's algorithm.)
For example, in a recipe where some steps have to happen before others, the transitive closure tells you, for every pair of steps, whether one has to come before the other:
It takes O(V³) time and O(V²) space, like the shortest-path version. Two notes:
-
reachable[i][i]only ends up true if i is on a cycle. If you want every node to count as reaching itself, set the diagonal to true before the loops. - If you only need one valid order for all the steps, not an answer for every pair, that's a topological sort, which takes O(V + E) time. Practice it with Recipe Step Order.
Common Floyd-Warshall Mistakes
-
Putting k anywhere but the outer loop. The i, j, k order looks reasonable and passes some tests, but it's wrong. See above.
-
Adding to "infinity." In Java or C++, if infinity is the biggest int, infinity plus anything positive overflows to a negative number. If infinity is just a big number like 1,000,000,000, then infinity plus a negative weight is less than infinity, and pairs with no path end up with fake, almost-infinite distances. Either way, check for infinity before adding.
-
Forgetting the diagonal. Set
dist[i][i]to 0 before the loops. If you leave it at infinity, the other distances still come out right, butdist[i][i]ends up as the length of the shortest cycle through i instead of 0. (That's a handy trick when you want the shortest cycle.) -
Overwriting parallel edges. If there are two edges between the same pair of nodes, keep the smaller weight.
-
Trusting the table when there's a negative cycle. Check the diagonal. If any entry is below 0, the distances and paths don't mean anything.
-
Using it on a huge graph. With 100,000 nodes, the table alone would need 10 billion entries. For big, sparse graphs, run Dijkstra's (or Bellman-Ford) from the nodes you care about instead.
Graph interview questions to practice
Each one walks you through a real coding interview problem one hint at a time.
- Cake Delivery Route » Find the fastest route for a bakery's delivery van when roads take different times and some are one-way. A Dijkstra's algorithm question, step by step.
- MeshMessage » You wrote a trendy new messaging app, MeshMessage, to get around flaky cell phone coverage. But messages are taking too long to send...
Your first 3 questions are free. Just sign in, no credit card. More Graph questions
See also:
Interview coming up?
Get the free 7-day email crash course. You'll learn how to think algorithmically, so you can break down tricky coding interview questions.
No prior computer science training necessary—we'll get you up to speed quickly, skipping all the overly academic stuff.
No spam. One-click unsubscribe whenever.
You're in! Head over to your email inbox right now to read day one!
Interview Cake