Floyd-Warshall
Advanced · 11 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Floyd-Warshall builds a full table of the shortest distance between every pair of places in one go. It is simple to code, and ideal when the network is small and you will look up many different pairs afterwards.
Practical use cases
- Web app: Distance table for warehouses. A logistics admin screen has 30 warehouses and staff constantly ask "how far is X from Y?". The system builds the 30 by 30 table once overnight, and every lookup afterwards is instant. Planners no longer wait for a route search on each click.
- Web app: Fare matrix for a metro app. A small city metro app has 40 stations. Pre-computing the cheapest fare or shortest time from every station to every other lets the app show a full fare chart and answer instantly, even offline.
- Web app: Who can reach whom in permissions. A role system lets role A include role B, and B include C. A table of "can A end up with C's rights?" answers every permission question with one lookup in an admin report.
- System: Network design and small dense graphs. Engineers compare how far every site is from every other when planning links, and puzzle tools use it because the code is only three nested loops.
The story: The Distance Chart on the Station Wall
Outside the railway station, Raju painted a big chart on the wall: places along the side, places across the top, and in each box the cheapest rickshaw fare from one place to another. People asked all day: "Market to school?", "Temple to hospital?" He wanted to answer any pair instantly.
At first the chart held only the direct fares, with blanks where no direct rickshaw ran. Mira had a plan to fill the blanks. "Pick one place, say the bus stand. Now for every pair, ask: would going through the bus stand be cheaper? If yes, update the box."
She did the same with the next place as a stopover, and the next, one place after another. By the time every place had had its turn as the stopover, every box held the true cheapest fare. Even routes with many changes got discovered gradually, since each round let routes use one more allowed stopover.
This tidy three-loop table-filling trick is the Floyd-Warshall algorithm: all-pairs shortest paths with a very short program.
How to spot this problem, and where you need it
You need the shortest distance between many or all pairs of places, on a fairly small network, and you will query the answers again and again.
Signs you need it
- The task says "all pairs", "distance between every two cities", or you plan to run a route search hundreds of times on the same small map.
- The number of nodes is small, a few hundred at most, so a table of nodes times nodes fits easily in memory.
- You need yes or no answers for "can A reach B at all" for every pair.
Where to use it in a project
- A back-office distance or fare matrix that is built once a night and read all day.
- A role or permission inheritance report showing which roles can eventually reach which rights.
The solution
Make a table dist[i][j] holding the direct cost between each pair, infinity when there is no link, and 0 on the diagonal. Then for each possible middle stop k, for each pair i and j, check whether going i to k to j is cheaper than the current number, and if so replace it. After every stop has been tried as the middle, the table holds the true shortest distance for all pairs.
Payoff: Before: 900 separate route searches each time the report loads. After: one table built once, and every pair is a single lookup.
Explain it like I am 8
You have a table of "how far from anywhere to anywhere". Take one friend's house as a meeting point. For every two houses, check if going via that friend's house is a shorter trip than the number you have written. Do this once with every house as the meeting point and the table is perfect.
How it works, step by step
- Build a table
d[i][j]: 0 on the diagonal, the road cost where a direct road exists, ∞ otherwise. - Loop k over every vertex (the allowed stopover), as the OUTERMOST loop.
- For every pair (i, j) check whether
d[i][k] + d[k][j] < d[i][j]and if so update it. - After the last k,
d[i][j]is the cheapest cost from i to j. - Negative cycle? If any
d[i][i]becomes negative, there is one.
The code in four languages
PHP
<?php
// $d: n x n matrix of direct costs (INF = no road, 0 on the diagonal).
// Fills it with the cheapest cost between every pair.
function floydWarshall(array $d): array {
$n = count($d);
for ($k = 0; $k < $n; $k++) { // allowed stopover (OUTER loop!)
for ($i = 0; $i < $n; $i++) {
for ($j = 0; $j < $n; $j++) {
if ($d[$i][$k] + $d[$k][$j] < $d[$i][$j]) {
$d[$i][$j] = $d[$i][$k] + $d[$k][$j]; // going via k is cheaper
}
}
}
}
return $d;
}
$names = ['A', 'B', 'C', 'D'];
$d = [
[0, 3, INF, 7],
[8, 0, 2, INF],
[5, INF, 0, 1],
[2, INF, INF, 0],
];
$res = floydWarshall($d);
foreach ($res as $i => $row) {
echo $names[$i] . ': ' . implode(' ', array_map(fn($x) => $x === INF ? 'INF' : $x, $row)) . "\n";
}JavaScript
// d: n x n matrix of direct costs (Infinity = no road, 0 on the diagonal).
// Returns a table with the cheapest cost between every pair.
function floydWarshall(d) {
const n = d.length;
const t = d.map(row => [...row]); // copy, keep the input safe
for (let k = 0; k < n; k++) { // allowed stopover (OUTER loop!)
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
if (t[i][k] + t[k][j] < t[i][j]) {
t[i][j] = t[i][k] + t[k][j]; // going via k is cheaper
}
}
}
}
return t;
}
const names = ['A', 'B', 'C', 'D'];
const I = Infinity;
const d = [
[0, 3, I, 7],
[8, 0, 2, I],
[5, I, 0, 1],
[2, I, I, 0],
];
floydWarshall(d).forEach((row, i) => console.log(names[i] + ': ' + row.join(' ')));Java
import java.util.*;
public class Main {
static final int INF = Integer.MAX_VALUE / 2; // big, but INF + INF still fits in an int
// d: n x n matrix of direct costs (INF = no road, 0 on the diagonal).
// Returns a table with the cheapest cost between every pair.
static int[][] floydWarshall(int[][] d) {
int n = d.length;
int[][] t = new int[n][];
for (int i = 0; i < n; i++) t[i] = d[i].clone(); // copy, keep the input safe
for (int k = 0; k < n; k++) { // allowed stopover (OUTER loop!)
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (t[i][k] + t[k][j] < t[i][j]) {
t[i][j] = t[i][k] + t[k][j]; // going via k is cheaper
}
}
}
}
return t;
}
public static void main(String[] args) {
String[] names = {"A", "B", "C", "D"};
int[][] d = {
{0, 3, INF, 7},
{8, 0, 2, INF},
{5, INF, 0, 1},
{2, INF, INF, 0},
};
int[][] res = floydWarshall(d);
for (int i = 0; i < res.length; i++) {
StringBuilder line = new StringBuilder(names[i] + ":");
for (int x : res[i]) line.append(' ').append(x >= INF ? "INF" : String.valueOf(x));
System.out.println(line);
}
}
}Go
package main
import (
"fmt"
"math"
)
const INF = math.MaxInt / 2 // big, but INF + INF still fits in an int
// floydWarshall takes an n x n matrix of direct costs (INF = no road, 0 on the diagonal).
// It returns a table with the cheapest cost between every pair.
func floydWarshall(d [][]int) [][]int {
n := len(d)
t := make([][]int, n)
for i := range d {
t[i] = append([]int(nil), d[i]...) // copy, keep the input safe
}
for k := 0; k < n; k++ { // allowed stopover (OUTER loop!)
for i := 0; i < n; i++ {
for j := 0; j < n; j++ {
if t[i][k]+t[k][j] < t[i][j] {
t[i][j] = t[i][k] + t[k][j] // going via k is cheaper
}
}
}
}
return t
}
func main() {
names := []string{"A", "B", "C", "D"}
d := [][]int{
{0, 3, INF, 7},
{8, 0, 2, INF},
{5, INF, 0, 1},
{2, INF, INF, 0},
}
for i, row := range floydWarshall(d) {
fmt.Print(names[i], ":")
for _, x := range row {
if x >= INF {
fmt.Print(" INF")
} else {
fmt.Print(" ", x)
}
}
fmt.Println()
}
}Time: O(V³) · Extra space: O(V²). Three simple nested loops over all vertices. Great for small graphs, too slow for huge ones.
Watch out for
- Putting the k loop inside the i and j loops. The stopover must be the outermost loop.
- Using a huge integer like 999999 for infinity and then adding two of them. Use a true infinity (INF / Infinity).
- Forgetting 0 on the diagonal, so a place seems to cost something to reach itself.
Quick check
- Floyd-Warshall answers…
- The cheapest path between every pair of vertices
- The cheapest path from one source to everyone
- Whether the graph is bipartite
- Which loop must be outermost?
- The one over i
- The one over k, the allowed stopover
- The one over j
- Time complexity?
- O(V²)
- O(V log V)
- O(V³)