Reading history

Floyd-Warshall Algorithm in C: All-Pairs Shortest Paths

6 min read 1 views

Implement the Floyd-Warshall algorithm in C to find shortest paths between every pair of vertices, rebuild routes, compute reachability and spot negative cycles.

Dijkstra and Bellman-Ford find the shortest paths from one starting vertex. Sometimes you need the shortest distance between every pair of vertices, for example to print a table of travel times between all towns on a map. The Floyd-Warshall algorithm does this with three nested loops and a single matrix. It is short enough to memorise, handles negative edges, and with a small change also tells you which vertices can reach which.

In this lesson you will learn

  • The idea of allowing one more intermediate vertex at a time
  • Implementing Floyd-Warshall in C with a distance matrix
  • Rebuilding routes with a next table
  • Reachability (transitive closure) with Warshall’s algorithm
  • Detecting negative cycles from the diagonal

You should know graphs and the Bellman-Ford algorithm.

All-Pairs Shortest Paths

#include <stdio.h>

#define V 4
#define INF 1000000000          /* "no road": large, but INF + INF still fits in a long long */

static void print_matrix(const char *title, long long d[V][V]) {
    printf("%s\n", title);
    for (int i = 0; i < V; i++) {
        for (int j = 0; j < V; j++) {
            if (d[i][j] >= INF) printf("  INF");
            else printf("%5lld", d[i][j]);
        }
        printf("\n");
    }
}

int main(void) {
    /* Travel times in minutes between four towns; INF = no direct road */
    long long d[V][V] = {
        {0,   5,   INF, 10 },
        {INF, 0,   3,   INF},
        {INF, INF, 0,   1  },
        {INF, INF, INF, 0  },
    };
    int next[V][V];
    for (int i = 0; i < V; i++)
        for (int j = 0; j < V; j++)
            next[i][j] = d[i][j] < INF ? j : -1;

    print_matrix("direct roads:", d);

    /* Floyd-Warshall: allow towns 0..k as stops, one k at a time */
    for (int k = 0; k < V; k++)
        for (int i = 0; i < V; i++)
            for (int j = 0; j < V; j++)
                if (d[i][k] + d[k][j] < d[i][j]) {
                    d[i][j] = d[i][k] + d[k][j];
                    next[i][j] = next[i][k];
                }

    print_matrix("shortest times between every pair:", d);

    /* Rebuild one route with the next[][] table */
    int u = 0, v = 3;
    printf("route %d to %d (%lld min): %d", u, v, d[u][v], u);
    while (u != v) {
        u = next[u][v];
        printf(" -> %d", u);
    }
    printf("\n");
    return 0;
}

Output

direct roads:
    0    5  INF   10
  INF    0    3  INF
  INF  INF    0    1
  INF  INF  INF    0
shortest times between every pair:
    0    5    8    9
  INF    0    3    4
  INF  INF    0    1
  INF  INF  INF    0
route 0 to 3 (9 min): 0 -> 1 -> 2 -> 3
  • The matrix d[i][j] starts with the direct road time from town i to town j, 0 on the diagonal, and a large INF where there is no road.
  • The outer loop picks a town k. For every pair (i, j) it asks: is going from i to k and then from k to j quicker than the best route found so far? After the loop for k finishes, d[i][j] is the shortest route that only stops at towns 0 to k on the way.
  • After all k values, every route is allowed, so the matrix holds the true shortest times. The direct road 0 → 3 takes 10 minutes, but 0 → 1 → 2 → 3 takes 9.
  • k must be the outermost loop. Putting it inside gives wrong answers.
  • INF is 109 stored in long long, so INF + INF cannot overflow.
  • next[i][j] is the first step from i towards j. When a shorter route through k is found, the first step becomes the first step towards k. Following next repeatedly prints the whole route.
  • Three nested loops over V vertices give O(V3) time and O(V2) memory.

Reachability and Negative Cycles

#include <stdio.h>

#define V 4

int main(void) {
    /* Transitive closure: can i reach j at all? (Warshall's algorithm) */
    int reach[V][V] = {
        {1, 1, 0, 0},
        {0, 1, 1, 0},
        {0, 0, 1, 0},
        {0, 0, 1, 1},
    };
    for (int k = 0; k < V; k++)
        for (int i = 0; i < V; i++)
            for (int j = 0; j < V; j++)
                reach[i][j] = reach[i][j] || (reach[i][k] && reach[k][j]);

    printf("reachability:\n");
    for (int i = 0; i < V; i++) {
        for (int j = 0; j < V; j++) printf("%2d", reach[i][j]);
        printf("\n");
    }

    /* Negative cycle check: after Floyd-Warshall, a negative d[i][i] means a cycle */
    const int INF = 1000000;
    int d[3][3] = { {0, 1, INF}, {INF, 0, -2}, {-1, INF, 0} };   /* cycle 0-1-2-0 costs -2 */
    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] < INF && d[k][j] < INF && d[i][k] + d[k][j] < d[i][j])
                    d[i][j] = d[i][k] + d[k][j];
    for (int i = 0; i < 3; i++)
        if (d[i][i] < 0) printf("town %d is on a negative cycle (d[%d][%d] = %d)\n", i, i, i, d[i][i]);
    return 0;
}

Output

reachability:
 1 1 1 0
 0 1 1 0
 0 0 1 0
 0 0 1 1
town 0 is on a negative cycle (d[0][0] = -2)
town 1 is on a negative cycle (d[1][1] = -2)
town 2 is on a negative cycle (d[2][2] = -4)
  • Replacing “minimum of sums” with “OR of ANDs” answers a yes/no question: can i reach j at all? This is Warshall’s algorithm for the transitive closure. Vertex 0 can reach 2 through 1, but nothing can reach 3 except 3 itself.
  • Floyd-Warshall works with negative edges, as long as there is no negative cycle.
  • If there is one, a vertex on the cycle can reach itself at a negative cost, so d[i][i] becomes negative. Checking the diagonal after the algorithm detects the cycle. The exact negative values are meaningless; only the sign matters.
  • The extra checks d[i][k] < INF && d[k][j] < INF stop negative edges from “improving” unreachable pairs, and stop int overflow.

Shortest Path Algorithms Compared

AlgorithmFindsNegative edgesTime
BFSOne source, unweightedn/aO(V + E)
DijkstraOne sourceNoO((V + E) log V)
Bellman-FordOne sourceYesO(V × E)
Floyd-WarshallAll pairsYesO(V3)

For a few hundred vertices, Floyd-Warshall is simple and fast enough. For large sparse graphs, running Dijkstra from every vertex is usually quicker.

Common Mistakes

  1. Putting k in an inner loop.
  2. Using INT_MAX as infinity in an int matrix, so INF + INF overflows to a negative number.
  3. Forgetting zeros on the diagonal at the start.
  4. Using it on huge graphs: 10,000 vertices means 1012 steps and a 108-cell matrix.

Practice Exercises

Exercise 1. After running Floyd-Warshall, find the town that can reach every other town and whose longest travel time is smallest (the best place for a central office).

Show answer
int best = -1;
long long best_worst = INF;
for (int i = 0; i < V; i++) {
    long long worst = 0;
    for (int j = 0; j < V; j++) {
        if (d[i][j] >= INF) { worst = INF; break; }   /* cannot reach j */
        if (d[i][j] > worst) worst = d[i][j];
    }
    if (worst < best_worst) { best_worst = worst; best = i; }
}

If best is still -1, no town can reach all the others. In the example graph that is the case, because nothing can travel back to town 0.

Exercise 2. How many times does the innermost line run for 100 vertices?

Show answer

1003 = 1,000,000 times, which takes only milliseconds.

Frequently Asked Questions

Why can Floyd-Warshall update the matrix in place?

During round k, the entries d[i][k] and d[k][j] do not change, because a route from i to k gains nothing by stopping at k itself. So reading and writing the same matrix gives the correct result.

Does Floyd-Warshall work on undirected graphs?

Yes. Store each undirected edge in both directions, d[u][v] and d[v][u]. Negative undirected edges are not allowed, because they form a negative cycle on their own.

Summary

  • Floyd-Warshall finds shortest distances between all pairs in O(V3).
  • Loop over the intermediate vertex k outermost.
  • A next table rebuilds routes; a negative diagonal means a negative cycle.
  • The same pattern with OR and AND gives reachability.

Next: Longest Common Subsequence in C.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *