DSA Notes
Master Floyd-Warshall algorithm completely — the all-pairs shortest path approach, the DP recurrence, step-by-step table filling, path reconstruction, negative cycle detection, transitive closure, and comparison with running Dijkstra V times.
What Is Floyd-Warshall?
Floyd-Warshall computes shortest paths between ALL pairs of vertices in a weighted graph. While Dijkstra finds shortest paths from ONE source, Floyd-Warshall gives you the complete distance matrix for every (source, destination) pair.
- Single-source shortest path: Dijkstra (non-negative), Bellman-Ford (any)
- All-pairs shortest path: Floyd-Warshall (any weights), or run Dijkstra V times
Complete Implementation
Step-by-Step Table Filling
| 0 | 1: 3, 0→3: 7, 1→2: 2, 2→0: 5, 2→3: 1, 3→0: 2 |
| 0 | 0 3 ∞ 7 |
| 1 | 8 0 2 ∞ |
| 2 | 5 ∞ 0 1 |
| 3 | 2 ∞ ∞ 0 |
Path Reconstruction
Transitive Closure
Floyd-Warshall can also compute whether any path exists between each pair (reachability):
Comparison: Floyd-Warshall vs Running Dijkstra V Times
For all-pairs shortest paths, you have two options:
| Approach | Time | Space | Handles Negative Weights |
|---|---|---|---|
| Floyd-Warshall | O(V³) | O(V²) | ✅ Yes |
| Dijkstra × V | O(V(V+E) log V) | O(V+E) | ❌ No |
| Bellman-Ford × V | O(V²E) | O(V) | ✅ Yes |
When Floyd-Warshall wins:
- Dense graphs (E ≈ V²): Dijkstra × V = O(V × V² × log V) = O(V³ log V) vs Floyd-Warshall O(V³)
- Negative weights present
- Simple implementation needed
When Dijkstra × V wins:
- Sparse graphs (E ≈ V): Dijkstra × V = O(V × (V+V) log V) = O(V² log V) < O(V³)
- No negative weights
Floyd-Warshall in Practice
# Network latency between all pairs of data centers
# V = 100 data centers, E = 500 connections
# Floyd-Warshall: 100³ = 10^6 operations — fast!
# Social network "degrees of separation" (unweighted)
# V = 10^6 users — Floyd-Warshall: 10^18 operations — impossible!
# Use BFS instead for large sparse graphs
# Practical limit: Floyd-Warshall viable for V ≤ 500-1000Summary
Floyd-Warshall: three nested loops over all vertex triples.
- Time: O(V³) — suitable for V ≤ 1000
- Space: O(V²) — always this, regardless of edges
- Handles negative weights: Yes (detects negative cycles via
dist[i][i] < 0) - Use for: All-pairs shortest paths, transitive closure, small dense graphs
*Next Lesson: Minimum Spanning Tree*
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Floyd-Warshall Algorithm — All-Pairs Shortest Paths with Complete Analysis.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Data Structures & Algorithms topic.
Search Terms
data-structures-algorithms, data structures & algorithms, data, structures, algorithms, graphs, floyd, warshall
Related Data Structures & Algorithms Topics