Skip to content

Floyd-Warshall, every pair

networks

Level 3 of 3

Also called Floyd-Warshall algorithm and All-pairs shortest paths.

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.

3114ABCE
Four one-way roads, each with its length. A to B is 3 by its own road and 2 round by E.
stoppairto the stop + from itin the cell beforewritten now
BA to C3 + 4 is 7empty7
BE to C1 + 4 is 5empty5
EA to B1 + 1 is 232
EA to C1 + 5 is 676
Every write in the run. The 5 in the last row is E to C, written at stop B. Stop A writes nothing, as no road leads into A, and stop C nothing, as no road leaves C. A to C is written twice.
fromto Ato Bto Cto E
A0261
B04
C0
E150
The table at the end. An empty cell means no way: no road leads into A, only A reaches E, and no road leaves C.
A way round beats a long road: 8 moments of its 14 steps, the steps between them left for the watch page
  1. step 1 of 14

    2223022ABCDEFABCDEFABCDEF0230022020020

    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.

    watch from here

  2. step 3 of 14

    2223022ABCDEFABCDEFABCDEF0230022020020

    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

    watch from here

  3. step 4 of 14

    2223022ABCDEFABCDEFABCDEF02430022020020

    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

    watch from here

  4. step 5 of 14

    2223022ABCDEFABCDEFABCDEF024304022020020

    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

    watch from here

  5. step 7 of 14

    2223022ABCDEFABCDEFABCDEF0246304022020020

    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

    watch from here

  6. step 11 of 14

    2223022ABCDEFABCDEFABCDEF02463040242020020

    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

    watch from here

  7. step 12 of 14

    2223022ABCDEFABCDEFABCDEF0246640242020020

    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

    watch from here

  8. step 14 of 14

    2223022ABCDEFABCDEFABCDEF02466402442020020

    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.

    watch from here

the steps, in plain words
  1. fill the table: 0 from each place to itself, and each road's lengthPython lines 9, 10, 11 and 12
  2. allow each place in turn as a stop on the wayPython line 13
  3. 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
  4. 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 nn 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 n3n^3, as section 4's question 1 derives.

pairs tried, ten times more at each mark up

a seconda minutea daya yearslope 3102104106108101010121014101610181020101102103104105106107a seconda minutean houra daya yearslope 3101102103104105106107108109101010111012101310141015101610171018101910201021101102103104105106107a seconda minutean houra daya yearslope 3101102103104105106107108109101010111012101310141015101610171018101910201021101102103104105106107

nn, 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
how long a line takes, at a billion pairs a second
nnpairs triedtime
1,000997,002,000about 997 milliseconds
100,000999,970,000,200,000about 12 days
10,000,000999,999,700,000,020,000,000about 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 nn 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.

what each case costs, and how fast that cost grows; section 4 works out every formula in it
besta star, one place with a road to every other placeworsta line, places one after another in letter order
pairs triedn(n−1)(n−2)n(n - 1)(n - 2)n(n−1)(n−2)n(n - 1)(n - 2)
ways made shorternone(n−1)(n−2)2\frac{(n - 1)(n - 2)}{2}
how the pairs tried grow in each case
tight, Θ\ThetaΘ(n3)\Theta(n^3)Θ(n3)\Theta(n^3)
ceiling, OOO(n3)O(n^3)O(n3)O(n^3)
floor, Ω\OmegaΩ(n3)\Omega(n^3)Ω(n3)\Omega(n^3)

extra memory: A table with room for n2n^2 numbers.

Extra memory is the room it needs on top of the input itself, while it runs.

111ABCF
A star of 4, from F. A way through a stop needs a road in and a road out, and no place here has both.
111ABCD
A line of 4. A to C, A to D and B to D each need a stop, so each is written once.
mapplacesroadspairs triedways made shorter
a star of 443240
a line of 443243
the small map44244
The pairs tried depend only on how many places there are. The ways made shorter depend on the roads.

where the formula comes from

Six questions, each worked line by line. Question 1 is the count the plot draws.

Question 1: how many pairs, PP, does a run try on nn places, whatever the roads?
  1. the move: each stop's pairs

    the line:
    each stop tries(n−1)(n−2) pairs\begin{gathered} \text{each stop tries} \\ (n - 1)(n - 2) \text{ pairs} \end{gathered}
    fromtrieswritten
    Ato C, to Eto C
    Cto A, to Enone
    Eto A, to Cto 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 n−1n - 1 places are left to start from. Each has n−2n - 2 left to end at, as it cannot end at itself. For 4 places, 3 times 2, which is 6.

  2. the move: every stop

    the line:
    P=n(n−1)(n−2)P = n(n - 1)(n - 2)

    why it is allowed: Each of the nn 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.

  3. the move: a ceiling

    the line:
    P≤n3P \le n^3

    why it is allowed: n−1n - 1 and n−2n - 2 are each below nn, so the product is below nn times nn times nn. For 4 places, PP is 24, at most 64.

  4. the move: read the bound

    the line:
    P∈O(n3)P \in O(n^3)

    why it is allowed: By line 3, with the fixed multiple 1. ∈\in reads is in, and O(n3)O(n^3) means at most a fixed multiple of n3n^3, from some nn on.

  5. the move: a floor

    the line:
    P≥n34P \ge \frac{n^3}{4}

    why it is allowed: From 4 places on, n−1n - 1 and n−2n - 2 are each at least half of nn. So the product is at least nn times half of nn times half of nn. For 4 places, PP is 24, at least 16.

  6. the move: read the bound

    the line:
    P∈Ω(n3)P \in \Omega(n^3)

    why it is allowed: By line 5, with the fixed multiple a quarter. Ω(n3)\Omega(n^3) means at least a fixed multiple of n3n^3, above 0, from some nn on.

  7. the move: both together

    the line:
    P∈Θ(n3)P \in \Theta(n^3)

    why it is allowed: Lines 4 and 6 bound PP by the same growth, only a fixed multiple apart. Θ(n3)\Theta(n^3) means both.

try it with a small nn: at n=4n = 4, line 2 gives P=24P = 24, which you can work out by hand

Question 2: a star makes no way shorter, so why does it try as many pairs, RR?
  1. the move: no way has a stop

    the line:
    on a star, everytry fails at once\begin{gathered} \text{on a star, every} \\ \text{try fails at once} \end{gathered}

    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.

  2. the move: the same count

    the line:
    R=n(n−1)(n−2)R = n(n - 1)(n - 2)

    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 Θ(n3)\Theta(n^3). For 4 places, 24.

try it with a small nn: at n=4n = 4, line 2 gives R=24R = 24, which you can work out by hand

Question 3: what does a stop read and what does it write? Let MM be the table's cells.
  1. the move: what a try reads

    the line:
    a try reads one cell in thestop’s column, one in its row,then its pair’s cell\begin{gathered} \text{a try reads one cell in the} \\ \text{stop's column, one in its row,} \\ \text{then its pair's cell} \end{gathered}

    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.

  2. the move: the first two stay put

    the line:
    a stop writes nothing inits own row or column\begin{gathered} \text{a stop writes nothing in} \\ \text{its own row or column} \end{gathered}
    at stop Eto Ato Bto Cto E
    Awrittenwrittenread
    B
    C
    Ereadread0
    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.

  3. the move: so one table

    the line:
    so the run writesover one table\begin{gathered} \text{so the run writes} \\ \text{over one table} \end{gathered}

    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.

  4. the move: room for every pair

    the line:
    M=n2M = n^2

    why it is allowed: The table has nn rows and nn 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.

try it with a small nn: at n=4n = 4, line 4 gives M=16M = 16, which you can work out by hand

Question 4: why is every cell right once all nn places have been stops? Let SS be the stops allowed.
  1. the move: only real ways

    the line:
    a number in the table is thelength of a way using onlystops allowed so far\begin{gathered} \text{a number in the table is the} \\ \text{length of a way using only} \\ \text{stops allowed so far} \end{gathered}

    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.

  2. the move: the promise

    the line:
    after k stops, each cell holds theshortest way using only those kplaces as stops\begin{gathered} \text{after } k \text{ stops, each cell holds the} \\ \text{shortest way using only those } k \\ \text{places as stops} \end{gathered}
    afterA to BA to CE to C
    the start3emptyempty
    stop A3emptyempty
    stop B375
    stop C375
    stop E265
    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: kk counts the places allowed so far, and this is the promise. With kk 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.

  3. the move: one more stop

    the line:
    with the new stop allowed,a shortest way avoids it,or passes it once\begin{gathered} \text{with the new stop allowed,} \\ \text{a shortest way avoids it,} \\ \text{or passes it once} \end{gathered}

    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 k−1k - 1 stops, and allow the kk-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.

  4. the move: split it there

    the line:
    cut at the new stop: two ways,each using only the first k−1places as stops\begin{gathered} \text{cut at the new stop: two ways,} \\ \text{each using only the first } k - 1 \\ \text{places as stops} \end{gathered}
    3114ABCE
    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.

  5. the move: after every stop

    the line:
    the promise holdsafter every stop\begin{gathered} \text{the promise holds} \\ \text{after every stop} \end{gathered}

    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 nn.

  6. the move: all the places

    the line:
    S=nS = n

    why it is allowed: SS is the last kk. With all nn 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.

try it with a small nn: at n=4n = 4, line 6 gives S=4S = 4, which you can work out by hand

Question 5: how many ways, WW, does a line make shorter?
  1. the move: stop by stop

    the line:
    W=1+2+⋯+(n−2)W = 1 + 2 + \dots + (n - 2)
    stopways written
    Anone
    BA to C
    CA to D, B to D
    Dnone
    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 n−2n - 2 at the last but one. The first and the last write none.

  2. the move: two copies

    the line:
    2W=(n−2)(n−1)2W = (n - 2)(n - 1)
    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 n−2n - 2 columns wide and n−1n - 1 tall. For 4 places, 2 columns of 3, which is 6.

  3. the move: halve it

    the line:
    W=(n−1)(n−2)2W = \frac{(n - 1)(n - 2)}{2}

    why it is allowed: Half of line 2, with its brackets in either order. For 4 places, 3.

try it with a small nn: at n=4n = 4, line 1 gives W=3W = 3, which you can work out by hand

Question 6: what does the whole method cost? Let TT be a ceiling on the code's steps.
  1. the move: what the code does

    the line:
    n zeros, m roads read twice,n3 choices of stop,start and end\begin{gathered} n \text{ zeros, } m \text{ roads read twice,} \\ n^3 \text{ choices of stop,} \\ \text{start and end} \end{gathered}
    the small maphow many
    zeros4
    roads read twice8
    choices of stop, start and end64
    of those, tried24
    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, nn 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.

  2. the move: add them

    the line:
    in all, n3+n+2m\begin{gathered} \text{in all, } n^3 + n + 2m \end{gathered}

    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.

  3. the move: a ceiling on the roads

    the line:
    T=n3+2n2+nT = n^3 + 2n^2 + n

    why it is allowed: With at most one road from a place to another, mm is below n2n^2, so 2m2m is below 2n22n^2. TT is this ceiling on line 2. For 4 places, 64 + 32 + 4, which is 100, and the small map's 76 is below it.

  4. the move: a simpler ceiling

    the line:
    T≤2n3T \le 2n^3

    why it is allowed: From 4 places on, n3n^3 is at least 4 times n2n^2, and that covers 2n2+n2n^2 + n. For 4 places, TT is 100, at most 128.

  5. the move: read the bound

    the line:
    T∈O(n3)T \in O(n^3)

    why it is allowed: By line 4, with the fixed multiple 2.

  6. the move: a floor

    the line:
    a run makes at leastn34 tries\begin{gathered} \text{a run makes at least} \\ \frac{n^3}{4} \text{ tries} \end{gathered}

    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.

  7. the move: both together

    the line:
    the whole method in Θ(n3),in books, Θ(V3)\begin{gathered} \text{the whole method in } \Theta(n^3), \\ \text{in books, } \Theta(V^3) \end{gathered}

    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 VV is the places.

try it with a small nn: at n=4n = 4, line 3 gives T=100T = 100, 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.

A>B 1, B>C 1, C>D 1, every step written down
stepwhat happenspairs triedways made shorter
1Fill 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.00
2Allow A as a stop on the way. For every pair of the other places, try going through A.00
3Allow B as a stop on the way. For every pair of the other places, try going through B.60
4From 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.71
5Allow C as a stop on the way. For every pair of the other places, try going through C.121
6From 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.142
7From 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.163
8Allow D as a stop on the way. For every pair of the other places, try going through D.183
9Done: 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.243

In all, 24 pairs tried. The formula from section 4, n(n−1)(n−2)n(n - 1)(n - 2), gives P=24P = 24 at n=4n = 4: 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.

methodfor every pairlengths below 0
this page's methodone table and one runnone here, as question 4 needs lengths of at least 1; books also take some below 0
Dijkstra's method, from each placeone run from each placecan be wrong, with no warning
Bellman-Ford, from each placeone run from each placeright, and it marks each place on or past a loop adding up below 0
Each of the other two has its own page, which shows a length below 0.
1,000 placesroadsDijkstra's looks, at most
a line999999,000
a road from every place to every other999,000999,000,000
This method tries 997,002,000 pairs on either map. By question 1 of Dijkstra's page, a run looks along each road at most once, so 1,000 runs look along at most 1,000 times the roads. That page also counts the work of choosing the nearest place.