A map app finds one route: from where you are to where you want to go. But sometimes you need all of them — the shortest distance between every pair of cities, every pair of routers, every pair of train stations, computed in advance so any later lookup is instant.
That is the all-pairs shortest path problem, and the Floyd-Warshall algorithm solves it with almost shocking economy: three nested loops over the nodes, and one line of arithmetic inside. Published by Robert Floyd in 1962 (building on Stephen Warshall's earlier work on transitive closure), it is one of the most elegant algorithms ever written.
The trick is a single, patient idea: let each node, one at a time, become a permitted stopover, and keep only the shortcuts it unlocks.
Comments
Loading comments...