Floyd-Warshall's algorithm

The Floyd-Warshall Algorithm is an efficient way to find all-pairs shortest paths on a graph. That is, it is guaranteed to find the shortest path between every pair of vertices in the graph.

The algorithm is based on the following observation: $$dist(i,j) \leq dist(i,k) + dist(k,j)$$, where $$i, j,$$ and $$k$$ are vertices and $$d(i,j)$$ is the distance between i and j in the graph. Thus, by starting with a known set of edges, we can incrementally improve the shortest paths between any edges.

The pseudocode below assumes an input graph of N vertices. $$d(i,j)$$ is $$\infty$$ if there is no edge from $$i$$ to $$j$$, and the length of the appropriate edge otherwise.

for i = 1 to N   for j = 1 to N        dist[i][j] = d(i,j)

for k = 1 to N   for i = 1 to N        for j = 1 to N            dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])

This will give the shortest distances between any two nodes, from which shortest paths may be constructed.

The algorithm takes $$O(N^3)$$ time and $$O(N^2)$$ space, and has the distinct advantage of hiding a small constant in its behavior, since very little work is done in the innermost loop.