Floyd-Warshall Algorithm for the ASSP
Use Floyd-Warshall to compute shortest paths between all pairs of nodes.
We'll cover the following...
In the next lessons, we’ll focus on the All Sources Shortest Path (ASSP) problem. Of course, we could solve the ASSP problem by just running Dijkstra’s algorithm once from each starting vertex. But the Floyd-Warshall algorithm, which was designed to specifically solve the ASSP problem, is a viable alternative. Its benefits are that it is very simple to implement and it runs faster than repeated Dijkstra executions on dense graphs.
The Floyd-Warshall algorithm
To explain how the Floyd-Warshall algorithm works, let’s look at a small example graph.
The Floyd-Warshall algorithm is remarkable in the sense that it is one of the few algorithms that uses the weighted adjacency matrix graph representation. Let’s assume that all edge weights are positive, so we can use a single matrix to represent the graph. The weighted adjacency matrix of our example graph is
The basic idea of Floyd-Warshall is to successively transform the adjacency matrix to end up with a resulting matrix that contains the lengths of the shortest paths between each pair of nodes.
In the following, let’s write for the number of nodes . In particular, the adjacency matrix is an matrix and the nodes of the graph are numbered .
The Floyd-Warshall algorithm successively computes a sequence of distance matrices
where can be obtained directly from the adjacency matrix and contains the end result.
Let’s look at the definition of these matrices .
Distance matrices: is the length of the shortest path from node to node that visits only intermediate nodes with an index less than .
So, the matrix contains the lengths of the shortest paths between each pair of nodes, assuming that the nodes with index are forbidden to visit in between. We’ll call such a path a -restricted shortest path.
Let’s take a deeper look at the first and last path matrix, and .
The matrix contains the lengths of shortest paths between any pair of nodes that visit only nodes with index in between. Since all nodes have an index , the matrix is our desired end result containing the lengths of the shortest paths between all pairs of nodes.
On the other hand, the matrix contains lengths of shortest paths between all pairs of nodes that may only visit nodes with index in between. Since there is no node with a negative index, the shortest paths can only be direct edges between nodes. Thus, we have
Here, we follow the convention that if no shortest path between two nodes exists, then their distance is infinite. Further, the shortest path from a node to itself is the empty path of length .
In particular, ...