Skip to main content
Examonaut

Topic 2 · Lesson 3 of 4

Floyd's algorithm

All-pairs shortest paths

Floyd's algorithm finds the shortest distance between every pair of vertices, and a way to recover each route. It uses two tables:

  • the distance table: initially the direct arc lengths, with ∞\infty where there is no direct arc;
  • the route table: initially every entry in a column is the letter of that column. The entry in row X, column Y tells you which vertex to go to first on the way from X to Y.

For a network with vertices A, B, C, ..., there is one iteration for each vertex in turn.

  1. In iteration kk, vertex kk is the intermediate vertex. Highlight its row and column.
  2. For every other entry, in row X and column Y, compare the current distance d(X,Y)d(X, Y) with d(X,k)+d(k,Y)d(X, k) + d(k, Y), the route through kk.
  3. If the route through kk is shorter, replace d(X,Y)d(X, Y) by d(X,k)+d(k,Y)d(X, k) + d(k, Y), and replace the route table entry in row X, column Y by the entry in row X, column kk.
  4. After the last iteration, the distance table holds the shortest distances.

To read a route from X to Y: look up row X, column Y to find the first vertex to visit, say P; then look up row P, column Y, and so on until you reach Y.

Worked example

One iteration

Three vertices: AB =4= 4, BC =3= 3, and no arc AC, so d(A,C)=∞d(A, C) = \infty.

Show solution
  1. Iteration 1 (via A): d(B,A)+d(A,C)=∞d(B, A) + d(A, C) = \infty, so nothing changes.
  2. Iteration 2 (via B): d(A,B)+d(B,C)=4+3=7<∞d(A, B) + d(B, C) = 4 + 3 = 7 < \infty, so d(A,C)d(A, C) and d(C,A)d(C, A) become 7. In the route table, row A, column C becomes the entry in row A, column B, which is B; row C, column A becomes B.
  3. Iteration 3 (via C): no improvements.

The route from A to C is: go to B (row A, column C), then from B to C (row B, column C is C): A B C, length 7.

Notes on Floyd's algorithm

  • On a directed network the tables are not symmetric, so every entry must be checked separately.
  • Floyd's algorithm has cubic order: nn iterations, each checking about n2n^2 entries.
  • The final distance table is the table of least distances used in the travelling salesman problem.

Practise this topic

Both are part of Premium.