Floyd-Warshall, every pair
how it works
The idea on a small map, then the whole method on one of the watch page's maps. Places keep their letters from the watch page's grid, A to D above and E to H below, so a map can skip a letter.
Floyd-Warshall finds the shortest way from every place to every other, all at once, in one table. A row is the place a way starts from, and a column the place it ends at. Fill in 0 from each place to itself, and each road's length. Every other cell stays empty. Now allow one place as a stop, and keep it allowed. For every pair of the other places, try going through it. Add the cell to the stop and the cell from it. If either is empty, the try fails at once. If the pair's own cell is empty or longer, write the sum there. Then allow the next place, in letter order, until every place has been a stop. Every length here is at least 1. This page counts the pairs tried, and the ways made shorter, a first number in an empty cell counting as one. The code below, in the language Python, does the same. Where the code says sorted, that only keeps letter order.
| stop | pair | to the stop + from it | in the cell before | written now |
|---|---|---|---|---|
| B | A to C | 3 + 4 is 7 | empty | 7 |
| B | E to C | 1 + 4 is 5 | empty | 5 |
| E | A to B | 1 + 1 is 2 | 3 | 2 |
| E | A to C | 1 + 5 is 6 | 7 | 6 |
| from | to A | to B | to C | to E |
|---|---|---|---|---|
| A | 0 | 2 | 6 | 1 |
| B | 0 | 4 | ||
| C | 0 | |||
| E | 1 | 5 | 0 |
step 1 of 14
Fill the table for the 6 places: 0 from each place to itself, and the length of each of the 6 roads. A pair with no road between them has no way yet.
what it remembers to know where it is
- stop allowed
- not yet
Where it says not yet, nothing is held there at that moment.
step 3 of 14
Allow B as a stop on the way. For every pair of the other places, try going through B.
what it remembers to know where it is
- stop allowed
- B
step 4 of 14
From A to B is 2, and from B to C is 2: 4 in all, shorter than any way found before. Write 4 for A to C.
what it remembers to know where it is
- stop allowed
- B
step 5 of 14
From A to B is 2, and from B to F is 2: 4 in all, shorter than any way found before. Write 4 for A to F.
what it remembers to know where it is
- stop allowed
- B
step 7 of 14
From A to C is 4, and from C to D is 2: 6 in all, shorter than any way found before. Write 6 for A to D.
what it remembers to know where it is
- stop allowed
- C
step 11 of 14
Allow F as a stop on the way. For every pair of the other places, try going through F.
what it remembers to know where it is
- stop allowed
- F
step 12 of 14
From A to F is 4, and from F to E is 2: 6 in all, shorter than any way found before. Write 6 for A to E.
what it remembers to know where it is
- stop allowed
- F
step 14 of 14
Done: every place has been allowed as a stop, so the table holds the shortest way for each of the 11 pairs with a way between them.
what it remembers to know where it is
- stop allowed
- not yet
Where it says not yet, nothing is held there at that moment.
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- fill the table: 0 from each place to itself, and each road's lengthPython lines 9, 10, 11 and 12
- allow each place in turn as a stop on the wayPython line 13
- for every pair, if going through the stop is shorter, write that in the tablePython lines 14, 15, 16, 17, 18, 19, 20, 21 and 22
- every place allowed: the table holds every shortest wayPython line 23
the same in Python
The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.
def floyd_warshall(roads):
"""Find the shortest way from every place to every other, at once.
roads is a list of (from, to, length), each running one way, at most one
from a place to another, none from a place to itself, each length at least
1. Returns a dict, a table, for each place: a dict of the places it has a way
to and how long the shortest is. A pair with no way is left out.
"""
places = sorted({place for a, b, _ in roads for place in (a, b)}) # letter order
ways = {place: {place: 0} for place in places} # 0 from each place to itself
for a, b, length in roads:
ways[a][b] = length # each road's length
for stop in places: # allow each place in turn as a stop
for a in places: # every ordered pair of the other places
for b in places:
if a == stop or b == stop or a == b:
continue
if stop not in ways[a] or b not in ways[stop]:
continue # no way through the stop yet
total = ways[a][stop] + ways[stop][b] # the way through the stop
if b not in ways[a] or total < ways[a][b]: # shorter?
ways[a][b] = total # write it in the table
return ways
how it scales
The plot counts the pairs tried on two maps of places, every road 1 long, measured from 10 to 1,000 places. One is a star, one place with a road to every other place. The other is a line in letter order.
Each mark across or up is ten times the one before. The two maps try as many pairs, so the plot draws them on top of each other. They climb three marks up for each mark across: 970,200 at 100 places and 997,002,000 at 1,000, about 1,028 times, near 10 times 10 times 10. Here the cost is the pairs tried, and a slope of 3 means it grows as , as section 4's question 1 derives.
pairs tried, ten times more at each mark up
, n, ten times more at each mark to the right
- a line, places one after another in letter ordersolid where measured by running it; dashed where its formula carries it on to ten millionslope 3: ten times n, 1,000 times the work
- a star, one place with a road to every other placesolid where measured by running it; dashed where its formula carries it on to ten million
| pairs tried | time | |
|---|---|---|
| 1,000 | 997,002,000 | about 997 milliseconds |
| 100,000 | 999,970,000,200,000 | about 12 days |
| 10,000,000 | 999,999,700,000,020,000,000 | about 31,688 years |
The pairs tried are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.
make these counts yourself
Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.
"""Count Floyd-Warshall's pairs tried yourself, as the plot on this page does.
Run it with Python 3.12 or later. For each size n it runs two maps of n
places: a star, one place with a road to every other, and a line. It prints the
pairs tried for each, and the same again by trying every pair one at a time, up
to 100 places. The counts are the same on any computer; only the time differs.
"""
def floyd_warshall(roads):
"""Find the shortest way from every place to every other, at once.
roads is a list of (from, to, length), each running one way, at most one
from a place to another, none from a place to itself, each length at least
1. Returns a dict, a table, for each place: a dict of the places it has a way
to and how long the shortest is. A pair with no way is left out.
"""
places = sorted({place for a, b, _ in roads for place in (a, b)}) # letter order
ways = {place: {place: 0} for place in places} # 0 from each place to itself
for a, b, length in roads:
ways[a][b] = length # each road's length
for stop in places: # allow each place in turn as a stop
for a in places: # every ordered pair of the other places
for b in places:
if a == stop or b == stop or a == b:
continue
if stop not in ways[a] or b not in ways[stop]:
continue # no way through the stop yet
total = ways[a][stop] + ways[stop][b] # the way through the stop
if b not in ways[a] or total < ways[a][b]: # shorter?
ways[a][b] = total # write it in the table
return ways
def count(roads):
"""How many pairs the run tries, quickly enough for 1,000 places.
A try with no way to the stop or none from it fails at once. So each stop
adds all its pairs in one sum, and works only on those with both ways known.
"""
places = sorted({place for a, b, _ in roads for place in (a, b)})
ways = {place: {place: 0} for place in places}
for a, b, length in roads:
ways[a][b] = length
tries = 0
for stop in places:
tries += (len(places) - 1) * (len(places) - 2)
onward = [(b, second) for b, second in ways[stop].items() if b != stop]
for a in places:
if a == stop or stop not in ways[a]:
continue
for b, second in onward:
if a != b and (b not in ways[a] or ways[a][stop] + second < ways[a][b]):
ways[a][b] = ways[a][stop] + second
return tries
def one_at_a_time(roads):
"""The same count, trying every ordered pair of the others in turn."""
places = {place for a, b, _ in roads for place in (a, b)}
tries = 0
for stop in places:
for a in places:
for b in places:
if a != stop and b != stop and a != b:
tries += 1
return tries
def names(n):
"""n names that sort in the order they count."""
return [f"p{k:04}" for k in range(1, n + 1)]
def star(n):
"""One place with a road to every other, each 1 long."""
places = names(n)
return [(places[0], b, 1) for b in places[1:]]
def line(n):
"""Places one after another in letter order, each road 1 long."""
places = names(n)
return [(places[k], places[k + 1], 1) for k in range(n - 1)]
if __name__ == "__main__":
print(f"{'n':>6} {'star':>13} {'line':>13} {'one at a time':>14}")
for n in [10, 100, 1000]:
by_hand = one_at_a_time(line(n)) if n <= 100 else "too many"
print(f"{n:>6} {count(star(n)):>13} {count(line(n)):>13} {by_hand:>14}")
best, worst and average
Best and worst often name the cheapest and the dearest input. Here no map is cheaper: any map of places tries as many pairs, as section 4's question 1 shows, and no run ends early. So no average is worked out for them. The names mark what does change, the ways made shorter. Best names a star, which makes none, the fewest there can be. Worst names a line, which makes one for each pair that needs a stop. A line is not the most: the small map makes one more on as many places.
A case is one kind of map, such as a star. A bound says how fast that case's cost grows as places are added.
The counts are in the grid. A count is often the sum of pieces that grow at different speeds, and on long inputs the fastest-growing piece swamps the rest. For example, a count of half of n times n, less half of n: at 2,000 items, 2,000,000 less 1,000. So how a cost grows is what tells one method from another, and the bounds keep just that.
| besta star, one place with a road to every other place | worsta line, places one after another in letter order | |
|---|---|---|
| pairs tried | ||
| ways made shorter | none | |
| how the pairs tried grow in each case | ||
| tight, | ||
| ceiling, | ||
| floor, | ||
extra memory: A table with room for numbers.
Extra memory is the room it needs on top of the input itself, while it runs.
| map | places | roads | pairs tried | ways made shorter |
|---|---|---|---|---|
| a star of 4 | 4 | 3 | 24 | 0 |
| a line of 4 | 4 | 3 | 24 | 3 |
| the small map | 4 | 4 | 24 | 4 |
where the formula comes from
Six questions, each worked line by line. Question 1 is the count the plot draws.
the move: each stop's pairs
the line:from tries written A to C, to E to C C to A, to E none E to A, to C to C Stop B on the small map, with roads A to B 3, A to E 1, E to B 1 and B to C 4. It has 3 places to start from and 2 pairs each. C has no way to B, and B has no way to A or E, so the other tries fail at once. why it is allowed: Set the stop aside, and places are left to start from. Each has left to end at, as it cannot end at itself. For 4 places, 3 times 2, which is 6.
the move: every stop
the line:why it is allowed: Each of the places is a stop once, and no run ends early. A try that fails at once still counts, so no road, length or letter changes this. For 4 places, 4 times 6, which is 24.
guess it, thenthe move: a ceiling
the line:why it is allowed: and are each below , so the product is below times times . For 4 places, is 24, at most 64.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 3, with the fixed multiple 1. reads is in, and means at most a fixed multiple of , from some on.
guess it, thenthe move: a floor
the line:why it is allowed: From 4 places on, and are each at least half of . So the product is at least times half of times half of . For 4 places, is 24, at least 16.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 5, with the fixed multiple a quarter. means at least a fixed multiple of , above 0, from some on.
guess it, thenthe move: both together
the line:why it is allowed: Lines 4 and 6 bound by the same growth, only a fixed multiple apart. means both.
guess it, then
try it with a small : at , line 2 gives , which you can work out by hand
the move: no way has a stop
the line:why it is allowed: A way through a stop needs a road into it and a road out. On a star, the place the roads leave has none coming in, and every other place has none going out.
the move: the same count
the line:why it is allowed: The code goes through every pair at every stop, and a try that fails at once still counts, as in question 1's lines 1 and 2. That question's lines 3 to 7 hold here too, so a star costs . For 4 places, 24.
guess it, then
try it with a small : at , line 2 gives , which you can work out by hand
the move: what a try reads
the line:why it is allowed: A to C at stop B reads A to B in column B and B to C in row B, then A to C. If either of the first two is empty, it stops there.
the move: the first two stay put
the line:at stop E to A to B to C to E A written written read B C E read read 0 Stop E on the small map, the two of its 6 tries that write, A to B and A to C. Row E and column E only get read. why it is allowed: The run never tries a pair that starts or ends at the stop, as it would gain nothing. A to B through stop B would be A to B, then B to B, and B to B is 0, so the sum is the same. Nor does it try a place to itself, as every length is at least 1, so nothing beats 0.
guess it, thenthe move: so one table
the line:why it is allowed: A stop tries each pair once, and the first two cells stay put. So no try reads a number written earlier in the same stop, and the order of pairs makes no difference. No second copy of the table is needed.
guess it, thenthe move: room for every pair
the line:why it is allowed: The table has rows and columns. The watch page draws every cell. The code keeps only the cells with a number, so at most this many. For 4 places, 16.
guess it, then
try it with a small : at , line 4 gives , which you can work out by hand
the move: only real ways
the line:why it is allowed: A road's length is such a way, and 0 is the way of no roads from a place to itself. A new number joins a way to the stop and a way from it, each using stops allowed so far. So no cell goes below the shortest way using those stops.
the move: the promise
the line:after A to B A to C E to C the start 3 empty empty stop A 3 empty empty stop B 3 7 5 stop C 3 7 5 stop E 2 6 5 Three cells of the small map. A to C's shortest way passes both B and E, so it comes only once E has been allowed. why it is allowed: counts the places allowed so far, and this is the promise. With at 0, a way has no stop. So it is a single road, or no road at all from a place to itself. That is what the table was filled with. An empty cell means no such way yet.
guess it, thenthe move: one more stop
the line:why it is allowed: Each stop carries the promise one further, so 0 stops gives 1, 1 gives 2, and so on. So take it as true after stops, and allow the -th place. A shortest way that avoids that place is in the cell already. A shortest way passes it at most once, as a place twice means a loop. Cutting out a loop makes a way shorter, as lengths are at least 1.
guess it, thenthe move: split it there
the line:A, E, B, C, drawn heavy, is 6. Cut at E, A to E has no stop and is 1, and E to C has stop B and is 5, both in the table before stop E. why it is allowed: Each part is the shortest using those stops, or the whole could be shorter. So by the promise the table has both parts, and by question 3 they stay put during this stop. The try adds them, so the cell gets that length or less, and by line 1 nothing lower.
guess it, thenthe move: after every stop
the line:why it is allowed: Line 2 starts it at 0 stops, and lines 3 and 4 carry it from each stop to the next, up to .
guess it, thenthe move: all the places
the line:why it is allowed: is the last . With all places allowed, any stops are allowed, so each cell holds the shortest way there is, and a cell still empty means no way. The promise names no order, so letter order is only this page's choice. For 4 places, 4.
guess it, then
try it with a small : at , line 6 gives , which you can work out by hand
the move: stop by stop
the line:stop ways written A none B A to C C A to D, B to D D none The line of 4, 0, 1, 2 and 0 ways, 3 in all. why it is allowed: Take a place on the line as the stop. By question 4's promise, the table now holds a way to it from each place before it. From it, the table holds only the road to the next place, as ways further on need later stops. So the stop writes one way for each place before it, into an empty cell. From 3 places on, as the stop, the second place writes 1, the third 2, and so on, up to at the last but one. The first and the last write none.
the move: two copies
the line:Two staircases of 1 and 2 squares fill 2 columns of 3, which is 6 squares. why it is allowed: Write the sum twice, the second backwards, as two staircases. Together they fill a block columns wide and tall. For 4 places, 2 columns of 3, which is 6.
guess it, thenthe move: halve it
the line:why it is allowed: Half of line 2, with its brackets in either order. For 4 places, 3.
guess it, then
try it with a small : at , line 1 gives , which you can work out by hand
the move: what the code does
the line:the small map how many zeros 4 roads read twice 8 choices of stop, start and end 64 of those, tried 24 Four places and 4 roads. why it is allowed: The code reads the roads once to list the places and once to fill the table, and writes a 0 for each place. Its last three lines that begin with for then choose a stop, a start and an end, choices each. It passes over those sharing a place, which leaves question 1's tries. The sort only keeps letter order, and by question 4 any order works, so it is left out.
the move: add them
the line:why it is allowed: Line 1's counts, leaving out the tries, which are among the choices. For the small map, 64 + 4 + 8, which is 76.
guess it, thenthe move: a ceiling on the roads
the line:why it is allowed: With at most one road from a place to another, is below , so is below . is this ceiling on line 2. For 4 places, 64 + 32 + 4, which is 100, and the small map's 76 is below it.
guess it, thenthe move: a simpler ceiling
the line:why it is allowed: From 4 places on, is at least 4 times , and that covers . For 4 places, is 100, at most 128.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 4, with the fixed multiple 2.
guess it, thenthe move: a floor
the line:why it is allowed: Every run makes all of question 1's tries, so that question's line 5 is a floor here too, from 4 places on.
guess it, thenthe move: both together
the line:why it is allowed: Lines 5 and 6 bound the whole method by the same growth, as a computer does each step in a fixed few actions. In books is the places.
guess it, then
try it with a small : at , line 3 gives , which you can work out by hand
count it yourself
A line of 4 in letter order, A, B, C and D, every road 1 long. The watch page writes this map as A>B 1, B>C 1, C>D 1, and A>B 1 means a road from A to B, 1 long. Within a stop, pairs go row by row. A try that writes nothing has no step of its own, so the pairs tried jump between steps. A stop's own step shows the count before its tries, so the 6 beside stop B are stop A's.
| step | what happens | pairs tried | ways made shorter |
|---|---|---|---|
| 1 | Fill the table for the 4 places: 0 from each place to itself, and the length of each of the 3 roads. A pair with no road between them has no way yet. | 0 | 0 |
| 2 | Allow A as a stop on the way. For every pair of the other places, try going through A. | 0 | 0 |
| 3 | Allow B as a stop on the way. For every pair of the other places, try going through B. | 6 | 0 |
| 4 | From A to B is 1, and from B to C is 1: 2 in all, shorter than any way found before. Write 2 for A to C. | 7 | 1 |
| 5 | Allow C as a stop on the way. For every pair of the other places, try going through C. | 12 | 1 |
| 6 | From A to C is 2, and from C to D is 1: 3 in all, shorter than any way found before. Write 3 for A to D. | 14 | 2 |
| 7 | From B to C is 1, and from C to D is 1: 2 in all, shorter than any way found before. Write 2 for B to D. | 16 | 3 |
| 8 | Allow D as a stop on the way. For every pair of the other places, try going through D. | 18 | 3 |
| 9 | Done: every place has been allowed as a stop, so the table holds the shortest way for each of the 6 pairs with a way between them. | 24 | 3 |
In all, 24 pairs tried. The formula from section 4, , gives at : the same.
where you meet it
A short paper from 1962 set it out, and ready-made code still offers it.
Floyd's 1962 paper
Robert Floyd printed the method in 1962 as Algorithm 97, a few lines long. Stephen Warshall published the same idea that year, for a table that says only yes or no: which place can reach which. So the method carries both names.
source: R. W. Floyd, Algorithm 97: Shortest path (opens in a new tab), Communications of the ACM 5(6), S. Warshall, A theorem on Boolean matrices (opens in a new tab), Journal of the ACM 9(1), and the books' volume three, chapter 35
networkx
networkx, ready-made Python code for networks, offers the method as floyd_warshall. Its last three lines that begin with for take every stop, start and end, as this page's code does.
source: the networkx source, its floyd_warshall_predecessor_and_distance in dense.py (opens in a new tab)
SciPy
SciPy, ready-made maths code for Python, offers it as floyd_warshall, and as the choice FW of shortest_path. It first turns the map into a full table, so its memory grows with every pair, however few the roads.
source: the SciPy source, _shortest_path.pyx (opens in a new tab), its shortest_path and floyd_warshall
what is used instead
From one start, use Dijkstra's method, or Bellman-Ford where a length can be below 0. For every pair on a map with few roads, run Dijkstra's method from each place, as section 7 sets out.
how it compares
This method answers every pair at once. Dijkstra's method and Bellman-Ford each answer from one start, so for every pair they run once from each place. A try and a look along a road each take a fixed few actions, so the two counts compare like with like. On a line of 1,000 places, Dijkstra's from each place makes at most 999,000 looks, about 1,000 times fewer than this method's tries. With a road from every place to every other, it makes at most 999,000,000, about the same as the tries. It also has the work of choosing the nearest place. So this method suits a map with many roads, and Dijkstra's from each place a map with few.
| method | for every pair | lengths below 0 |
|---|---|---|
| this page's method | one table and one run | none here, as question 4 needs lengths of at least 1; books also take some below 0 |
| Dijkstra's method, from each place | one run from each place | can be wrong, with no warning |
| Bellman-Ford, from each place | one run from each place | right, and it marks each place on or past a loop adding up below 0 |
| 1,000 places | roads | Dijkstra's looks, at most |
|---|---|---|
| a line | 999 | 999,000 |
| a road from every place to every other | 999,000 | 999,000,000 |