Floyd-Warshall Algorithm

In short: The Floyd-Warshall algorithm finds the shortest paths between every pair of nodes in a weighted graph using dynamic programming: for each node k in turn, it checks whether going through k shortens the path between each pair of nodes i and j. It handles negative edge weights, detects negative cycles (some dist[i][i] ends up below 0), and runs in O(V³) time and O(V²) space.

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:

  1. 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.
  2. For each node k (the outer loop), for each pair i, j: set dist[i][j] to dist[i][k] + dist[k][j] if that's smaller.
  3. 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:

dist[i][j] = weight of the edge from i to j (infinity if there's no edge) dist[i][i] = 0 for k from 0 to V - 1: # k MUST be the outer loop for i from 0 to V - 1: for j from 0 to V - 1: if dist[i][k] + dist[k][j] < dist[i][j]: dist[i][j] = dist[i][k] + dist[k][j] if any dist[i][i] < 0: the graph has a negative cycle

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, because dist[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:

import java.util.Arrays; private static final int UNREACHABLE = Integer.MAX_VALUE; // each edge is {fromNode, toNode, weight}, and nodes are numbered 0 to numNodes - 1 public static int[][] floydWarshall(int numNodes, int[][] edges) { // distances[i][j] starts as the weight of the edge from i to j: // 0 from a node to itself, and UNREACHABLE if there's no edge int[][] distances = new int[numNodes][numNodes]; for (int i = 0; i < numNodes; i++) { Arrays.fill(distances[i], UNREACHABLE); distances[i][i] = 0; } for (int[] edge : edges) { int fromNode = edge[0], toNode = edge[1], weight = edge[2]; // if two edges connect the same pair of nodes, keep the shorter one distances[fromNode][toNode] = Math.min(distances[fromNode][toNode], weight); } // k has to be the OUTER loop. after round k, distances[i][j] is the // shortest path from i to j that only stops at nodes 0 through k. for (int k = 0; k < numNodes; k++) { for (int i = 0; i < numNodes; i++) { for (int j = 0; j < numNodes; j++) { // skip it if i can't reach k or k can't reach j: // adding to Integer.MAX_VALUE would overflow if (distances[i][k] == UNREACHABLE || distances[k][j] == UNREACHABLE) { continue; } // is it shorter to go from i to j by way of k? if (distances[i][k] + distances[k][j] < distances[i][j]) { distances[i][j] = distances[i][k] + distances[k][j]; } } // if i can get back to itself for less than 0, there's a negative cycle if (distances[i][i] < 0) { throw new IllegalArgumentException("Graph has a negative cycle"); } } } return distances; } // int[][] edges = {{0, 1, 7}, {0, 2, 1}, {1, 3, 3}, {2, 0, 8}, {2, 3, -3}, {3, 1, 4}}; // floydWarshall(4, edges) returns // [0, 2, 1, -2] // [UNREACHABLE, 0, UNREACHABLE, 3] // [8, 1, 0, -3] // [UNREACHABLE, 4, UNREACHABLE, 0]

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] = j for every edge, and next[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 set next[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].

import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class AllPairsShortestPaths { private static final int UNREACHABLE = Integer.MAX_VALUE; private static final int NO_PATH = -1; private final int[][] distances; // nextNode[i][j] is the node right after i on the shortest path // from i to j, or NO_PATH if there's no path private final int[][] nextNode; // each edge is {fromNode, toNode, weight}, and nodes are numbered 0 to numNodes - 1 public AllPairsShortestPaths(int numNodes, int[][] edges) { distances = new int[numNodes][numNodes]; nextNode = new int[numNodes][numNodes]; for (int i = 0; i < numNodes; i++) { Arrays.fill(distances[i], UNREACHABLE); Arrays.fill(nextNode[i], NO_PATH); distances[i][i] = 0; nextNode[i][i] = i; } for (int[] edge : edges) { int fromNode = edge[0], toNode = edge[1], weight = edge[2]; if (weight < distances[fromNode][toNode]) { distances[fromNode][toNode] = weight; nextNode[fromNode][toNode] = toNode; } } for (int k = 0; k < numNodes; k++) { for (int i = 0; i < numNodes; i++) { for (int j = 0; j < numNodes; j++) { if (distances[i][k] == UNREACHABLE || distances[k][j] == UNREACHABLE) { continue; } if (distances[i][k] + distances[k][j] < distances[i][j]) { distances[i][j] = distances[i][k] + distances[k][j]; // the shortest path from i to j now starts out // the same way as the shortest path from i to k nextNode[i][j] = nextNode[i][k]; } } if (distances[i][i] < 0) { throw new IllegalArgumentException("Graph has a negative cycle"); } } } } public int getDistance(int start, int end) { return distances[start][end]; } public List<Integer> getPath(int start, int end) { List<Integer> path = new ArrayList<>(); if (nextNode[start][end] == NO_PATH) { return path; // there's no path from start to end } path.add(start); while (start != end) { start = nextNode[start][end]; path.add(start); } return path; } } // int[][] edges = {{0, 1, 7}, {0, 2, 1}, {1, 3, 3}, {2, 0, 8}, {2, 3, -3}, {3, 1, 4}}; // AllPairsShortestPaths shortestPaths = new AllPairsShortestPaths(4, edges); // shortestPaths.getDistance(0, 1) returns 2 // shortestPaths.getPath(0, 1) returns [0, 2, 3, 1] // shortestPaths.getPath(1, 0) returns []

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:

// each edge is {fromNode, toNode}, and nodes are numbered 0 to numNodes - 1 public static boolean[][] transitiveClosure(int numNodes, int[][] edges) { // reachable[i][j] is true if there's a path from i to j boolean[][] reachable = new boolean[numNodes][numNodes]; for (int[] edge : edges) { reachable[edge[0]][edge[1]] = true; } // the same loops as Floyd-Warshall, with "and" in place of "+" // and "or" in place of "min" for (int k = 0; k < numNodes; k++) { for (int i = 0; i < numNodes; i++) { for (int j = 0; j < numNodes; j++) { if (reachable[i][k] && reachable[k][j]) { reachable[i][j] = true; } } } } return reachable; } // recipe steps: 0 = mix the batter, 1 = bake the layers, // 2 = make the frosting, 3 = frost the cake. // an edge {a, b} means step a has to happen before step b. // int[][] edges = {{0, 1}, {1, 3}, {2, 3}}; // boolean[][] reachable = transitiveClosure(4, edges); // reachable[0][3] is true: mix the batter before you frost the cake // reachable[2][1] is false: the frosting and the baking don't depend on each 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, but dist[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.

Frequently Asked Questions

What is the Floyd-Warshall algorithm?

It's an all-pairs shortest path algorithm. It keeps a V by V table of distances and, for each node k in turn, replaces dist[i][j] with dist[i][k] + dist[k][j] whenever that's smaller. When it finishes, the table holds the shortest distance between every pair of nodes.

Why does k have to be the outer loop in Floyd-Warshall?

With k on the outside, the whole table is finished for paths that only stop at nodes 0 through k before node k + 1 is allowed. With k on the inside, each dist[i][j] gets settled once, using entries that haven't been improved yet, which gives wrong answers. The order of the i and j loops doesn't matter.

Does Floyd-Warshall work with negative edge weights?

Yes, as long as there's no negative cycle. If there is one, at least one diagonal entry dist[i][i] ends up below 0, which is how you detect it.

What is the time complexity of Floyd-Warshall?

O(V³) time, from three nested loops over the V nodes, and O(V²) space for the distance table. The running time doesn't depend on the number of edges.

When should you use Floyd-Warshall instead of Dijkstra's algorithm?

When you need distances between every pair of nodes in a small or dense graph, or when some edge weights are negative. For big, sparse graphs with no negative weights, running Dijkstra's algorithm from every node, in O(V(V + E) log V) time, is usually faster.

How do you reconstruct paths with Floyd-Warshall?

Keep a second table, next[i][j], holding the node right after i on the shortest path from i to j. Set it to j for each edge, change it to next[i][k] whenever going through k improves dist[i][j], and follow it from i until you reach j.

Reviewed by Stephen Cognetta, CEO of Aced. Last updated: December 4, 2026

. . .