A topic in the Open Knowledge Graph — a free, open map of 15,290 topics and the order to learn them in.

Floyd-Warshall Algorithm for All-Pairs Shortest Paths

Graduate Depth 95 in the knowledge graph ☐ I know this ☆ Set as goal
9topics build on this
602prerequisites beneath it
See this on the map →
Dynamic ProgrammingDijkstra's Algorithm+2 more→→Bellman-Ford Algorithm
shortest-path all-pairs dynamic-programming negative-weights transitive-closure

Core Idea

Floyd-Warshall computes shortest paths between all pairs of vertices in O(V³) time and O(V²) space using dynamic programming. It iterates through intermediate vertices k, updating distance[i][j] = min(distance[i][j], distance[i][k] + distance[k][j]). Unlike Dijkstra, it handles negative-weight edges (but not negative cycles) and is simple to implement.

How It's Best Learned

Trace the algorithm on a small graph, layer-by-layer through intermediate vertices k. Understand the recurrence relation and why the triple-nested loop works. Detect negative cycles by checking the diagonal. Compare to running Dijkstra V times.

Common Misconceptions

Explainer

You know Dijkstra's algorithm finds the shortest path from one source to all other vertices. But what if you need the shortest path between *every* pair of vertices — not just from one source, but from all of them? You could run Dijkstra V times (once from each vertex), but the Floyd-Warshall algorithm offers an elegant alternative built on dynamic programming, which you have already studied.

The algorithm maintains a V×V matrix `dist[i][j]` representing the best known distance from vertex i to vertex j. Initially, `dist[i][j]` is the weight of the direct edge from i to j (or infinity if no edge exists), and `dist[i][i]` is 0. Then comes the key insight: Floyd-Warshall iterates through every vertex k as a potential intermediate vertex and asks a simple question for every pair (i, j): "Is it shorter to go from i to j through k?" If `dist[i][k] + dist[k][j] < dist[i][j]`, then yes — update the distance. After considering all V possible intermediate vertices, the matrix contains the shortest path between every pair.

The recurrence relation makes this precise: `dist_k[i][j] = min(dist_{k-1}[i][j], dist_{k-1}[i][k] + dist_{k-1}[k][j])`, where the subscript k means "using only vertices 1 through k as intermediates." This is classic dynamic programming — building the solution by expanding the set of allowed intermediate vertices one at a time. The implementation is famously compact: three nested loops (for k, then i, then j), a single comparison, and a conditional update. The order of the loops matters — k must be the outermost loop — because each layer builds on the previous one.

A major advantage over Dijkstra is that Floyd-Warshall handles negative-weight edges correctly. Dijkstra's greedy strategy breaks when edges can be negative, but Floyd-Warshall's exhaustive dynamic programming approach works fine — it simply tries all intermediate paths and keeps the minimum. The one thing it cannot handle is negative-weight cycles (a cycle whose edge weights sum to a negative number), because you could traverse such a cycle infinitely to reduce the path length without bound. You can detect negative cycles by checking the diagonal of the result matrix: if any `dist[i][i] < 0`, vertex i is part of a negative cycle. The algorithm runs in O(V³) time and O(V²) space regardless of the number of edges, which makes it ideal for dense graphs but potentially wasteful for sparse ones where running Dijkstra from each vertex (with a priority queue) would be faster.

Practice Questions 5 questions

Prerequisite Chain

Understanding Zero → The Number Zero → Counting to Five → Counting to 10 → Counting to 20 → Counting a Set of Objects Up to 20 → Cardinality: The Last Number Counted → Matching Numerals to Quantities → Subitizing Small Quantities → Addition Within 10 → Number Bonds to 10 → Addition Within 20 → Doubles and Near Doubles → Doubles Facts Within 10 → Near Doubles Facts Within 20 → Mental Math Strategies for Addition → Mental Math: Adding and Subtracting Tens → Addition Within 100 → Repeated Addition as Multiplication → Multiplication as Equal Groups → Multiplication: Arrays → Basic Multiplication Facts (0s, 1s, 2s, 5s, 10s) → Multiplication Facts Within 100 → Division as Equal Sharing → Division as Grouping (Measurement Division) → Division: Grouping (Repeated Subtraction) Model → Division: Fair Sharing Model → Division as Equal Sharing → Division as Grouping → Basic Division Facts → Division Facts Within 100 → Multiplication and Division Fact Families → Relationship Between Multiplication and Division → Division Facts as Inverse of Multiplication → Remainders and Quotients in Division → Division Word Problems → Multi-Step Word Problems → Solving Multi-Step Word Problems → Multiplication Word Problems → Division Word Problems → Introduction to Long Division → Factors and Multiples → Prime and Composite Numbers → Equivalent Fractions → Relating Fractions and Decimals → Decimal Place Value → Integers and the Number Line → Comparing and Ordering Integers → Absolute Value → Adding Integers → Subtracting Integers → Multiplying Integers → Introduction to Exponents → Order of Operations → Integer Order of Operations → Variable Expressions → The Distributive Property → Variables and Expressions Review → Introduction to Polynomials → Adding and Subtracting Polynomials → Multiplying Polynomials → Factorial → Permutations → Combinations → Counting Principles: Addition and Multiplication Rules → Introduction to Graph Theory → Propositional Logic Foundations → Logical Equivalences → Boolean Algebra → Boolean Type and Truth Values → Comparison Operators and Boolean Tests → Logical Operators and Boolean Algebra → Conditional Statements → Defining and Calling Functions → Functions: Decomposing Problems → Function Parameters and Argument Passing → Return Values → Variable Scope → Introduction to Classes → Objects and Instances → Methods and Attributes → Algorithm Design Basics → Tree Structure and Node Properties → Binary Trees → Tree Traversals → Depth-First Search (DFS) → Depth-First Search: Implementation and Applications → Topological Sort → Dynamic Programming → Longest Common Subsequence (LCS) Problem → Edit Distance: Levenshtein Distance and DP → 0/1 Knapsack Problem: Bounded Capacity DP → Greedy Algorithms → Activity Selection Problem Using Greedy Algorithms → Dijkstra's Algorithm → Floyd-Warshall Algorithm for All-Pairs Shortest Paths

Longest path: 96 steps · 602 total prerequisite topics

Prerequisites (4)

Leads To (1)