Graph Theory37 sections · 1633 units
Open in Course

The Algorithm

(Three nested loops)

Floyd-Warshall computes all-pairs shortest paths with three nested loops:

for k from 1 to n
    for i from 1 to n
        for j from 1 to n
            dist[i][j] := min(dist[i][j], dist[i][k] + dist[k][j])

Before the loops, initialize dist[i][j] to edge weights (or infinity if no edge). Set dist[i][i] = 0.

Time: O(n3)O(n^3). Space: O(n2)O(n^2). Works with negative weights (but not negative cycles). Simple to code.