A road atlas often has a table of distances between every pair of cities. Computing such a table is the all-pairs shortest-path problem. The Floyd–Warshall algorithm solves it with three nested loops.
The idea
Intuition
First write down the direct distances. Then ask: “Can any trip get shorter if it is allowed to pass through city 1?” Update the table. Then “through city 1 or 2?”, and so on. After every city has been allowed as a stopover, the table holds the true shortest distances.
Number the vertices 1 , … , n 1, \dots, n 1 , … , n . Let d i j ( k ) d_{ij}^{(k)} d ij ( k ) be the length of the shortest path from i i i to j j j whose intermediate vertices all lie in { 1 , … , k } \{1, \dots, k\} { 1 , … , k } . A shortest such path either does not use k k k (so it is the best path with intermediates in { 1 , … , k − 1 } \{1, \dots, k-1\} { 1 , … , k − 1 } ), or uses k k k exactly once (so it is a best path from i i i to k k k followed by a best path from k k k to j j j ):
d i j ( k ) = min ( d i j ( k − 1 ) , d i k ( k − 1 ) + d k j ( k − 1 ) ) , d i j ( 0 ) = C i j . d_{ij}^{(k)} = \min\left(d_{ij}^{(k-1)},\; d_{ik}^{(k-1)} + d_{kj}^{(k-1)}\right), \qquad d_{ij}^{(0)} = C_{ij}. d ij ( k ) = min ( d ij ( k − 1 ) , d ik ( k − 1 ) + d k j ( k − 1 ) ) , d ij ( 0 ) = C ij .
C C C is the cost matrix: C i i = 0 C_{ii} = 0 C ii = 0 , C i j C_{ij} C ij = weight of edge ( i , j ) (i, j) ( i , j ) , and ∞ if there is no edge. This is dynamic programming : each table is built from the previous one. The same matrix can be updated in place, giving:
Floyd-Warshall Copy D = C
for k = 1 to n
for i = 1 to n
for j = 1 to n
if D[i][k] + D[k][j] < D[i][j] then
D[i][j] = D[i][k] + D[k][j]; P[i][j] = k
P[i][j] remembers the intermediate vertex, so paths can be rebuilt. Running time: O ( n 3 ) O(n^3) O ( n 3 ) ; space O ( n 2 ) O(n^2) O ( n 2 ) . It works with negative edges as long as there is no negative cycle.
Correction · Program 8.1 and the Floyd–Warshall recurrence
Study material says: In §8.3.4, d i k ( k − 1 ) d_{ik}^{(k-1)} d ik ( k − 1 ) is described as the “minimum path from j to k”. Program 8.1 contains if i = j then C[i][j] = 0 outside any loop, sets D[i][j] = 0; after the inner j loop, and uses J<N; J++ (capital J) in the innermost loop.
Correct version: d i k ( k − 1 ) d_{ik}^{(k-1)} d ik ( k − 1 ) is the shortest path from i to k. Set the diagonal inside the initialisation loop (D[i][i] = 0 for each i); declare and use one loop variable j; and, when ∞ is stored as a large integer, skip the update if D[i][k] or D[k][j] is ∞, to avoid overflow.
Why: After the inner loop has finished, j == N, so D[i][j] = 0 writes D[i][N], outside the row (undefined behaviour) instead of the diagonal. J is undeclared (C is case-sensitive), and if i = j then is not C. Adding two “infinite” values such as INT_MAX overflows. The recurrence itself is in Cormen et al., §25.2.
Example 8.10 All-pairs distances for Figure 8.5
Goal. Compute the distance matrix of Figure 8.5 (edges 1→2 3, 1→3 6, 1→5 9, 2→4 1, 3→4 8, 3→5 6, 4→5 6) and rebuild two paths.
Program. INF is a large value; additions with INF are skipped.
C · floyd.c Copy #include <stdio.h>
#define N 5
#define INF 1000000 /* "no path"; small enough that INF + INF fits in int */
int D[N][N], P[N][N];
void print_path( int i, int j) /* intermediate vertices from P, recursively */
{
int k = P[i][j];
if (k == - 1 ) return ;
print_path(i, k);
printf( " %d" , k + 1 );
print_path(k, j);
}
int main( void )
{
/* Figure 8.5 as a cost matrix (vertices 1..5 stored as 0..4) */
int C[N][N];
for ( int i = 0 ; i < N; i ++ )
for ( int j = 0 ; j < N; j ++ )
C[i][j] = (i == j) ? 0 : INF; /* C[i][i] = 0, no edge = INF */
C[ 0 ][ 1 ] = 3 ; C[ 0 ][ 2 ] = 6 ; C[ 0 ][ 4 ] = 9 ;
C[ 1 ][ 3 ] = 1 ; C[ 2 ][ 3 ] = 8 ; C[ 2 ][ 4 ] = 6 ; C[ 3 ][ 4 ] = 6 ;
for ( int i = 0 ; i < N; i ++ )
for ( int j = 0 ; j < N; j ++ ) {
D[i][j] = C[i][j];
P[i][j] = - 1 ; /* -1: direct edge, no intermediate */
}
for ( int k = 0 ; k < N; k ++ ) /* allow vertex k as an intermediate */
for ( int i = 0 ; i < N; i ++ )
for ( int j = 0 ; j < N; j ++ )
if (D[i][k] != INF && D[k][j] != INF &&
D[i][k] + D[k][j] < D[i][j]) {
D[i][j] = D[i][k] + D[k][j];
P[i][j] = k;
}
printf( "D (shortest distances; - means no path): \n " );
for ( int j = 0 ; j < N; j ++ ) printf( "%4d" , j + 1 );
printf( " \n " );
for ( int i = 0 ; i < N; i ++ ) {
printf( "%4d:" , i + 1 );
for ( int j = 0 ; j < N; j ++ )
if (D[i][j] == INF) printf( " -" );
else printf( "%4d" , D[i][j]);
printf( " \n " );
}
printf( "path 1 -> 5: 1" );
print_path( 0 , 4 );
printf( " 5 (length %d) \n " , D[ 0 ][ 4 ]);
printf( "path 2 -> 5: 2" );
print_path( 1 , 4 );
printf( " 5 (length %d) \n " , D[ 1 ][ 4 ]);
return 0 ;
}
Run it.
Output Copy D (shortest distances; - means no path):
1 2 3 4 5
1: 0 3 6 4 9
2: - 0 - 1 7
3: - - 0 8 6
4: - - - 0 6
5: - - - - 0
path 1 -> 5: 1 5 (length 9)
path 2 -> 5: 2 4 5 (length 7)
Read it. Row 1 equals Dijkstra’s answer from vertex 1. Entry (2, 5) became 7 when vertex 4 was allowed as an intermediate (2→4→5). The ”-” entries show pairs with no path (this DAG has no edges back to vertex 1).
Result. The matrix gives every shortest distance at once in O ( n 3 ) O(n^3) O ( n 3 ) ; for example d ( 2 , 5 ) = 7 d(2, 5) = 7 d ( 2 , 5 ) = 7 via 4.
Floyd–Warshall versus repeated Dijkstra
Floyd–Warshall Dijkstra from every vertex Time O ( n 3 ) O(n^3) O ( n 3 ) O ( n 3 ) O(n^3) O ( n 3 ) with arrays; O ( n ( n + e ) log n ) O(n(n + e)\log n) O ( n ( n + e ) log n ) with heapsNegative edges Allowed (no negative cycles) Not allowed Code Three loops More complex Best for Dense or small graphs Large sparse graphs
Key idea
Floyd–Warshall allows each vertex k k k in turn as an intermediate and keeps D [ i ] [ j ] = min ( D [ i ] [ j ] , D [ i ] [ k ] + D [ k ] [ j ] ) D[i][j] = \min(D[i][j], D[i][k] + D[k][j]) D [ i ] [ j ] = min ( D [ i ] [ j ] , D [ i ] [ k ] + D [ k ] [ j ]) ; after all n n n vertices the matrix holds all shortest distances, in O ( n 3 ) O(n^3) O ( n 3 ) time.
TEE Exam note
For “explain the all-pairs shortest-path algorithm” write the recurrence with its two cases, the triple loop, and the O ( n 3 ) O(n^3) O ( n 3 ) complexity; then work a 3- or 4-vertex example showing D ( 0 ) , D ( 1 ) , … D^{(0)}, D^{(1)}, \dots D ( 0 ) , D ( 1 ) , … . Check Your Progress 2, Q2: the complexity is O ( n 3 ) O(n^3) O ( n 3 ) .
Common mistake
Putting the k loop inside the i and j loops. The intermediate vertex k must be the outermost loop; otherwise some paths are not considered.
Common mistake
Initialising the diagonal to ∞. D [ i ] [ i ] D[i][i] D [ i ] [ i ] must start at 0 (no cost to stay where you are).
Key takeaways
Recurrence: d i j ( k ) = min ( d i j ( k − 1 ) , d i k ( k − 1 ) + d k j ( k − 1 ) ) d_{ij}^{(k)} = \min(d_{ij}^{(k-1)}, d_{ik}^{(k-1)} + d_{kj}^{(k-1)}) d ij ( k ) = min ( d ij ( k − 1 ) , d ik ( k − 1 ) + d k j ( k − 1 ) ) .
Three nested loops with k k k outermost: O ( n 3 ) O(n^3) O ( n 3 ) time, O ( n 2 ) O(n^2) O ( n 2 ) space.
Diagonal 0, missing edges ∞; guard against ∞ + ∞ overflow.
Works with negative edges if there is no negative cycle; P P P rebuilds the paths.
Practice questions Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 1 · multiple choice What is the time complexity of the Floyd–Warshall algorithm?
Check answer
Show answer Answer: C. O ( n 3 ) O(n^3) O ( n 3 )
Three nested loops of n n n iterations each. O ( n e ) O(ne) O ( n e ) is Bellman–Ford.
Question 2 · multiple choice Which loop must be the outermost in Floyd–Warshall?
Check answer
Show answer Answer: C. The loop over k k k (allowed intermediate vertex)
The recurrence builds D ( k ) D^{(k)} D ( k ) from D ( k − 1 ) D^{(k-1)} D ( k − 1 ) ; all pairs must be updated for one k k k before the next k k k is allowed.
Question 3 · multiple choice With D [ i ] [ k ] = 4 D[i][k] = 4 D [ i ] [ k ] = 4 , D [ k ] [ j ] = 3 D[k][j] = 3 D [ k ] [ j ] = 3 and D [ i ] [ j ] = 9 D[i][j] = 9 D [ i ] [ j ] = 9 , what is D [ i ] [ j ] D[i][j] D [ i ] [ j ] after processing k k k ?
A 9 B 4 C 12 D 7
Check answer
Show answer Answer: D. 7
4 + 3 = 7 < 9 4 + 3 = 7 < 9 4 + 3 = 7 < 9 , so the path through k k k is better.
Question 4 · multiple choice What should D [ i ] [ i ] D[i][i] D [ i ] [ i ] be at the start?
Check answer
Show answer Answer: A. 0
The cost from a vertex to itself is 0 (if there are no negative cycles).
Question 5 · multiple choice What does this program print?
C · q8-floyd.c Copy #include <stdio.h>
#define INF 1000
int main( void )
{
int D[ 3 ][ 3 ] = {{ 0 , 8 , 2 },
{INF, 0 , INF},
{INF, 3 , 0 }};
for ( int k = 0 ; k < 3 ; k ++ )
for ( int i = 0 ; i < 3 ; i ++ )
for ( int j = 0 ; j < 3 ; j ++ )
if (D[i][k] + D[k][j] < D[i][j])
D[i][j] = D[i][k] + D[k][j];
printf( "%d %d \n " , D[ 0 ][ 1 ], D[ 2 ][ 0 ]);
return 0 ;
} A 8 1000 B 5 1000 C 5 3 D 2 1000
Check answer
Show answer Answer: B. 5 1000
0→2→1 costs 2 + 3 = 5 < 8 2 + 3 = 5 < 8 2 + 3 = 5 < 8 . There is no path from 2 to 0, so D [ 2 ] [ 0 ] D[2][0] D [ 2 ] [ 0 ] stays INF (1000). (INF is small here, so INF + INF does not overflow.)
Question 6 · short answer
Write the Floyd–Warshall algorithm and state its time complexity and the condition under which it works.
Show worked answer Input: cost matrix C C C with C [ i ] [ i ] = 0 C[i][i] = 0 C [ i ] [ i ] = 0 , C [ i ] [ j ] C[i][j] C [ i ] [ j ] = weight of edge ( i , j ) (i, j) ( i , j ) , ∞ if no edge. Algorithm: set D = C D = C D = C and P [ i ] [ j ] = − 1 P[i][j] = -1 P [ i ] [ j ] = − 1 ; for k = 1 k = 1 k = 1 to n n n : for i = 1 i = 1 i = 1 to n n n : for j = 1 j = 1 j = 1 to n n n : if D [ i ] [ k ] + D [ k ] [ j ] < D [ i ] [ j ] D[i][k] + D[k][j] < D[i][j] D [ i ] [ k ] + D [ k ] [ j ] < D [ i ] [ j ] then D [ i ] [ j ] = D [ i ] [ k ] + D [ k ] [ j ] D[i][j] = D[i][k] + D[k][j] D [ i ] [ j ] = D [ i ] [ k ] + D [ k ] [ j ] and P [ i ] [ j ] = k P[i][j] = k P [ i ] [ j ] = k . At the end D [ i ] [ j ] D[i][j] D [ i ] [ j ] is the shortest distance from i i i to j j j , and P P P gives the intermediate vertices. Time O ( n 3 ) O(n^3) O ( n 3 ) , space O ( n 2 ) O(n^2) O ( n 2 ) . It works with negative edge weights provided the graph has no negative-weight cycle.