Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Graphs/Floyd-Warshall

Learn the pattern · ~15 min

Floyd-Warshall

also called all-pairs shortest path, transitive closure

Allow the cities as stopovers one at a time. After city k is allowed, every pair's entry is the shortest route using only stopovers 0 to k.

SignalsV <= ~400-500all-pairs distances or reachabilitysmall alphabet/state graph (26 letters)Learn first1D / Fibonacci-style
Cheat sheet and practice

Reach for it when you read

  • +"Shortest distance between every pair", or many distance queries between arbitrary nodes.
  • +n is small (up to about 400), so n³ steps are affordable.
  • +Reachability between all pairs: "is a a prerequisite of b?" for many (a, b).
  • +A tiny alphabet or set of states with conversion costs (26 letters, 10 digits): all pairs first, then sum.

Not this one when

  • ×One source, large graph: Dijkstra (weights ≥ 0) or Bellman-Ford.
  • ×Only "connected or not" in an undirected graph: union-find or BFS.
  • ×Unweighted graph with large n: BFS from each source you need.

Learn Floyd-Warshall

First, what does "all pairs" mean?

Dijkstra and Bellman-Ford answer "from this one source, how far is everything?". Sometimes you need the shortest distance between every pair of nodes: from 0 to 3, from 2 to 4, from 4 to 1, all of them. With n nodes that's an n × n table, d[i][j] = the cheapest cost from i to j.

Floyd-Warshall fills that whole table at once. Its idea fits in one question, asked over and over: is it cheaper to go from i to j through k?

C++
d[i][j] = min(d[i][j], d[i][k] + d[k][j]);

How do we allow one stopover at a time?

Five cities, two-way roads, a-b (cost):

23821101234
roads (both ways): 0-1 (2), 0-4 (8), 1-2 (3), 1-4 (2), 2-3 (1), 3-4 (1)

Start the table with only the roads: d[i][j] is the road's cost, ∞ where there's no direct road, and 0 on the diagonal (i to i costs nothing). The rule:

For k = 0, then 1, then 2, …: for every pair (i, j), allow k as a stopover. If d[i][k] + d[k][j] beats d[i][j], take it.

Each round allows one more city as a stopover. (Pairs are listed once; the table is symmetric.)

via what happens what improves
0 every route through 0 is longer than what we have nothing
1 0→1→2 = 2 + 3, 0→1→4 = 2 + 2, 2→1→4 = 3 + 2 0-2: ∞ → 5, 0-4: 8 → 4, 2-4: ∞ → 5
2 0→2→3 = 5 + 1, 1→2→3 = 3 + 1 0-3: ∞ → 6, 1-3: ∞ → 4
3 2→3→4 = 1 + 1 2-4: 5 → 2
4 0→4→3 = 4 + 1, 1→4→3 = 2 + 1 0-3: 6 → 5, 1-3: 4 → 3

Look at round 4: 0→4→3 uses d[0][4] = 4, which itself came from round 1 (through 1). So the final 5 is really 0 → 1 → 4 → 3. Each round builds on the earlier ones.

The code for it

C++
vector<vector<long long>> allPairs(int n, vector<vector<int>>& edges) {
    const long long INF = 1e18;
    vector<vector<long long>> d(n, vector<long long>(n, INF));
    for (int i = 0; i < n; i++) d[i][i] = 0;   // staying put costs nothing
    for (auto& e : edges) {                    // two-way roads: fill both directions
        d[e[0]][e[1]] = min(d[e[0]][e[1]], (long long)e[2]);
        d[e[1]][e[0]] = min(d[e[1]][e[0]], (long long)e[2]);
    }
    for (int k = 0; k < n; k++)                // the stopover: outermost, always
        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][j] = min(d[i][j], d[i][k] + d[k][j]);
    return d;
}

You don't need to memorise this. It's the table: three loops, the stopover k outside, and every pair inside. The < INF check stops ∞ + ∞ from overflowing.

Why is it fine to overwrite d while round k is still running? Because the two numbers round k reads, d[i][k] and d[k][j], don't change during round k: going through k to reach k means d[i][k] + d[k][k], and d[k][k] is 0 (with no negative cycle), so it can't beat d[i][k]. One table is enough.

Fine, but how does this help us?

The classic problem: Find the City With the Smallest Number of Neighbors at a Threshold Distance. Return the city that can reach the fewest other cities within distanceThreshold. On a tie, return the largest index.

Same roads, threshold 4. Solve it by hand: for each city, find which others you can reach for at most 4.

city reachable within 4 how you found it count
0 1, 4 1 by road; 4 via 1 (2 + 2); 2 and 3 cost 5 2
1 0, 2, 3, 4 roads to 0, 2, 4; 3 via 4 (2 + 1) 4
2 1, 3, 4 roads to 1, 3; 4 via 3 (1 + 1); 0 costs 5 3
3 1, 2, 4 roads to 2, 4; 1 via 4 (1 + 2); 0 costs 5 3
4 0, 1, 2, 3 roads to 1, 3; 0 via 1, 2 via 3 4

City 0 reaches the fewest, so the answer is 0.

The brute force

For every start city, walk every simple path (no city twice) and keep the cheapest cost to each city you reach.

C++
vector<vector<long long>> allPairsSlow(int n, vector<vector<int>>& edges) {
    vector<vector<pair<int, int>>> adj(n);
    for (auto& e : edges)
        adj[e[0]].push_back({e[1], e[2]}), adj[e[1]].push_back({e[0], e[2]});
    vector<vector<long long>> d(n, vector<long long>(n, LLONG_MAX));
    vector<bool> onPath(n, false);
    function<void(int, int, long long)> go = [&](int src, int u, long long cost) {
        d[src][u] = min(d[src][u], cost);
        onPath[u] = true;
        for (auto [v, w] : adj[u])
            if (!onPath[v]) go(src, v, cost + w);   // every simple path, one by one
        onPath[u] = false;
    };
    for (int s = 0; s < n; s++) go(s, s, 0);
    return d;
}

It gives the same table, but the number of paths explodes. If every pair of cities has a road, 12 cities already have about 10⁸ simple paths from one start, and the whole run takes about 10 seconds at -O2. LeetCode allows 100 cities. Hopeless. (Running Dijkstra from every city would work too, with more code; Floyd-Warshall is shorter and handles one-way negative roads.)

The one thought that fixes it

Stop at the pair (0, 3). Its best route is 0 → 1 → 4 → 3, cost 5. Look at its largest-numbered stopover: 4. Cut the route there:

  • 0 → 1 → 4 is a best route from 0 to 4 whose stopovers are all below 4 (just 1). Cost 4.
  • 4 → 3 is a best route from 4 to 3 with no stopovers at all. Cost 1.

Every best route splits like that, at its largest stopover k, into two best routes with stopovers below k. So once we know all best routes using stopovers 0..k−1, one sweep over the pairs gives all best routes using 0..k. The n² answers are built out of each other.

That's the rounds from step 2, and it's why k must be the outermost loop: when round k reads d[i][k] and d[k][j], they must be finished for stopovers 0..k−1, which is only true once round k − 1 has covered every pair.

Put k innermost instead (for i, for j, for k), and d[0][3] is finished at j = 3, before d[0][4] drops from 8 to 4 at j = 4. The best it finds is through 2: 5 + 1 = 6, not 5. One loop order, wrong answer.

The problem's code, on top of allPairs:

C++
int findTheCity(int n, vector<vector<int>>& edges, int distanceThreshold) {
    auto d = allPairs(n, edges);
    int best = -1, bestCount = INT_MAX;
    for (int i = 0; i < n; i++) {
        int count = 0;
        for (int j = 0; j < n; j++)
            if (j != i && d[i][j] <= distanceThreshold) count++;
        if (count <= bestCount) bestCount = count, best = i;   // <=: a tie goes to the larger index
    }
    return best;
}

Dry run

The finished table, row by row, threshold 4:

city row of d within 4 (j ≠ i) count best so far
0 0 2 5 5 4 1, 4 2 city 0, count 2
1 2 0 3 3 2 0, 2, 3, 4 4 city 0
2 5 3 0 1 2 1, 3, 4 3 city 0
3 5 3 1 0 1 1, 2, 4 3 city 0
4 4 2 2 1 0 0, 1, 2, 3 4 city 0

City 0, the same answer as the brute force. The <= in the code is the tie rule: a later city with an equal count replaces the earlier one.

Why it's O(n³)

Count what happens to each pair: in each of the n rounds, every one of the n² pairs is checked once. That's n³ steps, O(n³) time, and the table is O(n²) space. For n = 400 that's 6.4 × 10⁷ steps, fine. For n = 10⁴ it's 10¹², so with a big graph and one source, use Dijkstra.

From an explosion of paths down to n³, by building each best route out of two shorter best routes.

Only "can i reach j?" Use true/false

Course Schedule IV asks, for many pairs, whether one course is a prerequisite of another, directly or not. Same three loops, booleans instead of costs:

C++
if (reach[i][k] && reach[k][j]) reach[i][j] = true;   // i reaches k, k reaches j

With 0 → 1 and 1 → 2, round 1 sets reach[0][2], and reach[2][0] stays false.

Remember this

  • "Every pair", or many distance queries between any two nodes, and n up to about 400 → Floyd-Warshall.
  • The stopover loop k is outermost. Always.
  • The diagonal starts at 0, two-way roads fill both d[a][b] and d[b][a], and never add to ∞.
  • Whenever a problem asks for distances between many pairs in a small graph, build the table once and answer each question with a lookup.

Practise it on Find the City With the Smallest Number of Neighbors, then Shortest Routes II (the table, then queries), Course Schedule IV (true/false), Evaluate Division (multiply instead of add) and Minimum Cost to Convert String I (26 letters are the nodes).

Below, watch Find the City run line by line.

Watch it work, line by line

City With the Smallest Number of Neighbors at a Threshold Distance ↗, n = 4, roads 0-1:3 1-2:1 1-3:4 2-3:1, threshold 4 → 3. Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.

Loading the walkthrough…

When to use it, and when not

Ask yourself

Do I need answers for every pair (or many arbitrary pairs), and is n small, around 400 or less?

Reach for it when

  • +V <= ~400-500
  • +all-pairs distances or reachability
  • +small alphabet/state graph (26 letters)
  • +V3 <= ~1e8

It fails when

  • ×V in the thousands (O(V³) is too slow)use Dijkstra from each needed source
  • ×Only single-source queriesuse Dijkstra (or Bellman-Ford with negative edges)

Recall card

Answer each one out loud before you open it. Come back in three days and try again without reading the page.

  • 1Which loop must be outermost, and why?Reveal

    k, the stopover. Only then are d[i][k] and d[k][j] already shortest using stopovers below k when you combine them.

  • 2When should you choose Floyd-Warshall over running Dijkstra?Reveal

    When you need many or all pairs and n is small (about 400 or less), or there are negative edges.

  • 3How does Floyd-Warshall reveal a negative cycle?Reveal

    Some diagonal entry d[i][i] ends up negative.

Practice ladder

every problem →
  1. 1Find the City With the Smallest Number of Neighbors at a Threshold Distancethe hookMedium
  2. 2Shortest Routes IIall pairs, then queriesMedium
  3. 3Course Schedule IVreachability onlyMedium
  4. 4Evaluate Divisionratios that multiplyMedium
  5. 5Minimum Cost to Convert String Ia tiny alphabet as the graphMedium
  6. 6Network Delay Timesmall n, one source: Floyd still worksMedium

Finished Floyd-Warshall? Mark it done and Lessgo moves you to the next step.

Start the climb9 steps from E-Rank to S, with a coachPractise itthe cheat sheet and every problem, easy to OA level
Back to Floyd-Warshall

On this page

The lessonWatch it workThe templateWhen to use itRecallPractice ladder
TodayReviewPatternsProblems

The template: frame and slot · every line explained, then clean C++, Java and Python to revise from

Start the free 7-day trial