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 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.
- In iteration , vertex is the intermediate vertex. Highlight its row and column.
- For every other entry, in row X and column Y, compare the current distance with , the route through .
- If the route through is shorter, replace by , and replace the route table entry in row X, column Y by the entry in row X, column .
- 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 , BC , and no arc AC, so .
Show solutionHide solution
- Iteration 1 (via A): , so nothing changes.
- Iteration 2 (via B): , so and 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.
- 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: iterations, each checking about entries.
- The final distance table is the table of least distances used in the travelling salesman problem.
Practise this topic
Quiz me on this topic10 questions, marked as you go.Make a practice paperPick the marks and difficulty. Print it with a mark scheme.
Both are part of Premium.