Floyd-Warshall
O(V³)
For every intermediate node k, test whether routing i→k→j beats the current i→j distance.
Learn first1D / Fibonacci-style
0%
mastery
0/5 solved
0/5 solved
Recognise it
The signal
Shortest paths or reachability between all pairs on a small graph: V up to ~400-500, or a small state graph like 26 letters.
1Brute force
Run Dijkstra from every vertex (fine too for sparse graphs).
2The observation
Per-source recomputation: one DP over intermediate vertices.
3Why it works
After iteration k, dist[i][j] is the shortest path using only intermediates from {0..k}.
Reach for it when
- +all-pairs distances or reachability
- +small alphabet/state graph (26 letters)
Not 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)
Practice
0/5 solved
- Find the City With the Smallest Number of Neighbors at a Threshold DistanceFoundationFoundationMedium
- Shortest Routes IIApply it · All-pairs queries at n = 500.Apply itCSESMedium
- Course Schedule IVOne change · Reachability, not distance.One changeMedium
- Evaluate DivisionTwists · Path weights multiply.TwistsGoogle, UberMedium
- Minimum Cost to Convert String IMastery checkMastery checkMedium
Pitfalls
Classic bugs
- !
k(the intermediate) must be the outermost loop; puttingiorjoutside gives wrong distances.