Lesson 3 · Graphs and Trees

Floyd–Warshall Algorithm

Find the shortest distance between every pair of vertices by letting one more vertex act as a stepping stone in each round, and read negative cycles straight off the diagonal.

Floyd–Warshall Algorithm concept diagramA triangle of vertices i, k and j comparing the direct distance with the detour through k, beside five bars showing the allowed middle vertices growing from none to all four.one relaxation: is the detour through k shorter?dist[i][j] — best found so fardist[i][k]dist[k][j]ikjdist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])one more middle vertex per roundD⁰{ }D¹{A}D²{A, B}D³{A, B, C}D⁴{A, B, C, D}D⁴ allows every vertex: the answerk is the OUTER loop — round k only reads the finished matrix from round k − 1
1

All Pairs in One Run

  1. Problem – all-pairs shortest paths: the shortest distance from every vertex to every other vertex.
  2. Input – a weighted directed graph with V vertices. Negative edges are allowed; a negative cycle is detected, not solved.
  3. Output – a V × V matrix where dist[i][j] is the shortest distance from i to j.
  4. Technique – dynamic programming: grow the set of vertices a path may pass through, one vertex per round.
  5. Cost – O(V³) time, O(V²) space, no priority queue and no graph traversal.

The Floyd–Warshall algorithm (also called Floyd's algorithm or the Roy–Floyd–Warshall algorithm) computes the shortest path between every pair of vertices in one run. Where Dijkstra's algorithm and Bellman–Ford answer one source to all vertices, this one answers all sources to all vertices and returns the whole distance matrix.

It works on a matrix, not on a queue of vertices. Start with the direct edge weights, then repeatedly ask of every cell: would the path be shorter if it went through vertex k? After every vertex has had its turn as k, the matrix holds the true shortest distances. The whole algorithm is three nested loops and one min.

  • All-pairs, not single-source: one run fills a V × V table
  • Works with negative edge weights, unlike Dijkstra
  • Detects a negative cycle through the diagonal of the result
  • Three nested loops, so the running time does not depend on the number of edges
2

The DP Recurrence

  1. Initialise – dist[i][i] = 0, dist[i][j] = w(i, j) for each edge, and ∞ for every missing edge.
  2. Pick k – for k = 1 to V, allow vertex k as an intermediate (middle) vertex.
  3. Relax every pair – for each i and j, set dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]).
  4. Repeat – after round k, every path may use any of vertices 1..k in its middle.
  5. Finish – after round V every vertex is allowed, so each cell is the shortest distance.

Define Dᵏ[i][j] as the length of the shortest path from i to j whose intermediate vertices all come from {1, 2, …, k}. D⁰ allows no intermediate vertex at all, so it is just the adjacency matrix. The answer is Dⱽ, where every vertex is allowed.

The recurrence follows from one observation. The best path from i to j using vertices up to k either does not use k — then it is Dᵏ⁻¹[i][j] — or it uses k exactly once, splitting into i → k and k → j, each using only vertices up to k − 1. So Dᵏ[i][j] = min(Dᵏ⁻¹[i][j], Dᵏ⁻¹[i][k] + Dᵏ⁻¹[k][j]). That is optimal substructure over a growing vertex set, which is why this is a dynamic programming algorithm.

Why k must be the outer loop. Round k reads Dᵏ⁻¹ for the pairs (i, k) and (k, j). Those values must be final for the smaller vertex set before round k starts. With k outermost, every round sees a finished previous round. Put i or j outermost and a cell is used before the vertices it depends on have been considered, which gives wrong answers.

Why one matrix is enough. Row k and column k do not change during round k: Dᵏ[i][k] = min(Dᵏ⁻¹[i][k], Dᵏ⁻¹[i][k] + Dᵏ⁻¹[k][k]), and Dᵏ⁻¹[k][k] is 0 without a negative cycle. So the algorithm can overwrite a single matrix in place, and space drops from O(V³) to O(V²).

  • State: shortest i → j path using only vertices 1..k in the middle
  • Transition: skip k, or pass through k once
  • k outermost is required for correctness, not only for speed
  • In-place update is safe because row k and column k stay fixed in round k
3

Pseudocode and Path Reconstruction

  1. for k in 0..V-1 – the vertex being admitted as a middle vertex.
  2. for i in 0..V-1 – every source.
  3. for j in 0..V-1 – every destination.
  4. if dist[i][k] + dist[k][j] < dist[i][j] – the detour through k is shorter.
  5. dist[i][j] = dist[i][k] + dist[k][j] and next[i][j] = next[i][k] – store the new length and the first hop.

The distance matrix tells you how far, not which way. Floyd–Warshall path reconstruction needs one more matrix. To print the route, keep a second V × V matrix next, where next[i][j] is the first vertex after i on the best known path to j. Initialise it to j for every edge (i, j). Whenever a detour through k wins, the path to j now starts the same way as the path to k, so next[i][j] = next[i][k].

To rebuild the path from u to v, start at u and keep jumping u = next[u][v] until you reach v. Each jump is one edge, so rebuilding costs O(path length). If next[u][v] is empty, v is unreachable from u.

In code, ∞ needs care. Adding two ∞ values overflows a fixed-width integer and can wrap to a negative number that looks like a short path. Either skip the update when either half is ∞, or use a sentinel such as INT_MAX / 2 that survives one addition.

  • next[i][j] stores the first hop, so a path is rebuilt by repeated lookup
  • Update next in the same if that updates dist
  • Guard ∞ + ∞ against integer overflow
  • An empty next[u][v] means no path exists
Key reference

Terms, operations, and practical uses

Terms to know

  • All-pairs shortest pathThe shortest distance for every ordered pair (i, j), returned as a V × V matrix.
  • Intermediate vertexA vertex on a path other than its two ends. Round k allows vertices 1..k here.
  • RelaxationReplacing dist[i][j] with dist[i][k] + dist[k][j] when that is smaller.
  • Transitive closureReachability for every pair; the boolean form of the same loop (Warshall's algorithm).
Implementation

Code in Python, C++ and Java

INF = float("inf")


def floyd_warshall(n, edges):
    dist = [[0 if i == j else INF for j in range(n)] for i in range(n)]
    nxt = [[j if i == j else None for j in range(n)] for i in range(n)]
    for u, v, w in edges:
        dist[u][v] = w
        nxt[u][v] = v

    # k is the newest vertex allowed in the middle of a path, so it must be
    # the outermost loop.
    for k in range(n):
        for i in range(n):
            for j in range(n):
                if dist[i][k] + dist[k][j] < dist[i][j]:
                    dist[i][j] = dist[i][k] + dist[k][j]
                    nxt[i][j] = nxt[i][k]

    has_negative_cycle = any(dist[v][v] < 0 for v in range(n))
    return dist, nxt, has_negative_cycle


def path(nxt, u, v):
    if nxt[u][v] is None:
        return []
    route = [u]
    while u != v:
        u = nxt[u][v]
        route.append(u)
    return route


names = "ABCD"
edges = [(0, 1, 3), (0, 3, 7), (1, 0, 8), (1, 2, 2), (2, 0, 5), (2, 3, 1), (3, 0, 2)]
dist, nxt, negative = floyd_warshall(4, edges)

for name, row in zip(names, dist):
    print(name, " ".join(str(d) for d in row))
print("C to B:", " -> ".join(names[v] for v in path(nxt, 2, 1)), "=", dist[2][1])
print("negative cycle:", str(negative).lower())
#include <iostream>
#include <string>
#include <vector>
using namespace std;

const int INF = 1e9;

struct Edge {
    int from, to, weight;
};

int main() {
    const int n = 4;
    const string names = "ABCD";
    vector<Edge> edges = {{0, 1, 3}, {0, 3, 7}, {1, 0, 8}, {1, 2, 2},
                          {2, 0, 5}, {2, 3, 1}, {3, 0, 2}};

    vector<vector<int>> dist(n, vector<int>(n, INF));
    vector<vector<int>> nxt(n, vector<int>(n, -1));
    for (int v = 0; v < n; v++) {
        dist[v][v] = 0;
        nxt[v][v] = v;
    }
    for (const Edge& e : edges) {
        dist[e.from][e.to] = e.weight;
        nxt[e.from][e.to] = e.to;
    }

    // k is the newest vertex allowed in the middle of a path, so it must be
    // the outermost loop.
    for (int k = 0; k < n; k++) {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (dist[i][k] == INF || dist[k][j] == INF) continue;
                if (dist[i][k] + dist[k][j] < dist[i][j]) {
                    dist[i][j] = dist[i][k] + dist[k][j];
                    nxt[i][j] = nxt[i][k];
                }
            }
        }
    }

    for (int i = 0; i < n; i++) {
        cout << names[i];
        for (int j = 0; j < n; j++) cout << " " << dist[i][j];
        cout << "\n";
    }

    int u = 2, v = 1;
    cout << "C to B: " << names[u];
    while (u != v) {
        u = nxt[u][v];
        cout << " -> " << names[u];
    }
    cout << " = " << dist[2][1] << "\n";

    bool negative = false;
    for (int x = 0; x < n; x++) negative = negative || dist[x][x] < 0;
    cout << "negative cycle: " << (negative ? "true" : "false") << "\n";
    return 0;
}
import java.util.Arrays;

public class Main {
    static final int INF = Integer.MAX_VALUE / 2;

    public static void main(String[] args) {
        int n = 4;
        String names = "ABCD";
        int[][] edges = {{0, 1, 3}, {0, 3, 7}, {1, 0, 8}, {1, 2, 2},
                         {2, 0, 5}, {2, 3, 1}, {3, 0, 2}};

        int[][] dist = new int[n][n];
        int[][] next = new int[n][n];
        for (int i = 0; i < n; i++) {
            Arrays.fill(dist[i], INF);
            Arrays.fill(next[i], -1);
            dist[i][i] = 0;
            next[i][i] = i;
        }
        for (int[] e : edges) {
            dist[e[0]][e[1]] = e[2];
            next[e[0]][e[1]] = e[1];
        }

        // k is the newest vertex allowed in the middle of a path, so it must
        // be the outermost loop.
        for (int k = 0; k < n; k++) {
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    if (dist[i][k] + dist[k][j] < dist[i][j]) {
                        dist[i][j] = dist[i][k] + dist[k][j];
                        next[i][j] = next[i][k];
                    }
                }
            }
        }

        for (int i = 0; i < n; i++) {
            StringBuilder row = new StringBuilder().append(names.charAt(i));
            for (int d : dist[i]) row.append(' ').append(d);
            System.out.println(row);
        }

        int u = 2, v = 1;
        StringBuilder route = new StringBuilder().append(names.charAt(u));
        while (u != v) {
            u = next[u][v];
            route.append(" -> ").append(names.charAt(u));
        }
        System.out.println("C to B: " + route + " = " + dist[2][1]);

        boolean negative = false;
        for (int x = 0; x < n; x++) negative |= dist[x][x] < 0;
        System.out.println("negative cycle: " + negative);
    }
}
Watch it run

Step through it

Running on A→B 3, A→D 7, B→A 8, B→C 2, C→A 5, C→D 1, D→A 2

3782512ABCDdistance matrix: not filled yetAABBCCDD∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞goal: shortest distance for all 16 ordered pairs3782512ABCDdistance matrix: not filled yetAABBCCDD∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞goal: shortest distance for all 16 ordered pairs
Step 1

The graph: 4 vertices, 7 directed edges

Floyd–Warshall answers every source at once: the shortest distance from each vertex to each other vertex. The input is a weighted directed graph, here with no negative cycle.

Output
1 / 20
4

A Solved Example, Round by Round

  1. Graph – vertices 1, 2, 3; edges 1→2 = 4, 1→3 = 11, 2→1 = 6, 2→3 = 2, 3→1 = 3.
  2. D⁰ – direct edges; 3→2 has no edge, so it starts at ∞.
  3. k = 1 – 3→2 = min(∞, 3 + 4) = 7. Nothing else improves.
  4. k = 2 – 1→3 = min(11, 4 + 2) = 6.
  5. k = 3 – 2→1 = min(6, 2 + 3) = 5.
  6. Answer – D³ = [[0, 4, 6], [5, 0, 2], [3, 7, 0]].

This is the format an exam answer should follow: state the graph, write D⁰, then write one matrix per round and mark the cells that changed. For each changed cell, show the comparison that changed it. Examiners award the method marks for the intermediate matrices, not only for the final one.

Notice what each round can and cannot do. In round k = 1, only paths of the form i → 1 → j are new, so only 3→2 benefits: before, 3 had no edge to 2, but 3 → 1 → 2 costs 3 + 4 = 7. The row and column of vertex 1 stay the same, exactly as the in-place argument predicts. The diagonal stays 0 throughout, which confirms there is no negative cycle.

461132123exam graph: 3 vertices, 5 edgesD⁰ direct12310411260233∞0D¹ via 11230411602370D² via 2123046602370D³ via 3123046502370shaded cell = the one pair that round improves3→2: ∞ → 7 · 1→3: 11 → 6 · 2→1: 6 → 5
  • Write D⁰ first: edge weights, 0 on the diagonal, ∞ elsewhere
  • One matrix per round; mark only the cells that changed
  • Row k and column k never change in round k — a quick self-check
  • End by checking the diagonal for a negative value
5

Time and Space Complexity

Time complexity is Θ(V³). The three loops each run V times and the body is constant work, so the algorithm always does exactly V³ comparisons, whatever the number of edges. The best, average and worst case are the same.

Space complexity is Θ(V²) for the distance matrix, plus another V² for next if paths are needed. The naive DP would keep V + 1 matrices (Θ(V³) space); the in-place update removes that.

Because the cost ignores E, the algorithm is at its best on dense graphs, where E is close to V². On a sparse graph, running Dijkstra's algorithm from every vertex costs O(V · E log V), which is far less than V³ when E is about V. At V = 1,000, V³ is one billion simple operations: fine in C++, slow in Python.

  • No early exit: a sparse graph costs as much as a complete one
  • Rebuilding one path from next takes O(V), one lookup per edge
  • Memory can run out before time does: 10,000 vertices need 10⁸ cells
6

Negative Edges and Negative Cycles

The algorithm is correct with negative edge weights, because it never finalises a vertex early the way Dijkstra does — every pair is reconsidered in every round. This is the main reason to prefer it over running Dijkstra from each source.

A negative cycle is different: going around it again always lowers the cost, so shortest paths through it do not exist. The algorithm still terminates, and Floyd–Warshall negative cycle detection costs nothing extra. If a vertex v lies on a negative cycle, the cycle is a path from v back to v with negative length, so after the run dist[v][v] < 0. Check the diagonal once at the end: any negative entry means a negative cycle exists.

A pair (i, j) is affected when i can reach some vertex v with dist[v][v] < 0 and v can reach j. Those distances should be reported as −∞ rather than as the numbers left in the matrix.

  • Negative edges: handled correctly
  • Negative cycle: detected by a negative diagonal entry
  • Pairs that can route through such a vertex have no shortest path (−∞)
  • Dijkstra fails on negative edges; Bellman–Ford handles them from one source
7

Floyd–Warshall vs Dijkstra vs Bellman–Ford

All three solve shortest paths, but they answer different questions at different costs. Use the table to choose: the deciding facts are how many sources you need, whether weights can be negative, and how dense the graph is.

The same triple loop has other uses. Replace min and + with or and and and it computes the transitive closure (Warshall's algorithm): whether j is reachable from i at all. Replace them with max and min and it finds the widest (maximum bottleneck) path between every pair.

Choosing a shortest-path algorithm
Floyd–WarshallDijkstraBellman–Ford
SourcesAll pairsOne sourceOne source
Negative edgesYesNoYes
Negative cycleDetected (diagonal)Not handledDetected (extra pass)
TimeΘ(V³)O((V + E) log V)O(V · E)
Best forDense graphs, all pairsLarge sparse graphs, one sourceNegative edges, one source
  • Need every pair on a dense or small graph: Floyd–Warshall
  • Need one source with non-negative weights: Dijkstra
  • Need one source with negative edges: Bellman–Ford
  • All pairs on a large sparse graph with negative edges: Johnson's algorithm