Say we want to find the shortest path between every pair of vertices in G. Edge lengths could be negative, but there are no negative cycles.

Floyd-Warshall

This algorithm uses Dynamic Programming. The subproblems are:

  • The answer is
    • So we either use or not
  • The base case is just limiting to be 0 where we get if or if .
  • Note that here, k just refers to a node in the graph that we are allowed to use
procedure floyd-warshall(G, â„“)

Input: Directed graph G = (V, E); edge lengths â„“_e with no negative cycles.
Output: For all u, v ∈ V, where |V| = n, dist(u, v, n) is the shortest path distance from u to v

for i = 1, ..., n:
    for j = 1, ..., n:
        dist(i, j, 0) = ∞

for all (i, j) ∈ E:
    dist(i, j, 0) = â„“(i, j)

for k = 1, ..., n:
    for i = 1, ..., n:
        for j = 1, ..., n:
            dist(i, j, k) = min {
                dist(i, j, k - 1),
                dist(i, k, k - 1) + dist(k, j, k - 1)
            }

The runtime here is .