Implementation of Floyd-Warshall

Learn about the details of implementing Floyd-Warshall.

Implementation notes

The implementation of Floyd-Warshall is relatively straightforward compared to Dijkstra’s algorithm. We’ll construct the matrices A0,P0A_0, P_0 from the weighted adjacency list and then iteratively compute the distance and predecessor matrices Ak,PkA_k, P_k, for k=1,,Vk = 1, \ldots, |V|.

One important observation to reduce the memory footprint of the algorithm is that the computation of Ak+1A_{k+1} and Pk+1P_{k+1} depends only on the immediate previous matrices AkA_k and PkP_k. Therefore, the updates to the distance and predecessor matrices can be done in place. In other words, we only need to store one pair of n×nn \times n matrices instead of all of them. This reduces the memory requirements from O(V3)\mathcal{O}(|V|^3) to O(V2)\mathcal{O}(|V|^2).

Another implementation detail is how to represent the infinite values in the distance matrices. A pragmatic and often feasible solution is to use a large constant value such as one billion to represent infinity. The main concern here is that this value should be larger than the maximum length of a shortest path in the graph, to avoid overflows or incorrect results.

Get hands-on with 1200+ tech skills courses.