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

O(V³)

For every intermediate node k, test whether routing i→k→j beats the current i→j distance.

  1. 1Learnthe lesson(you are here)
  2. 2Guidedwatch it run, line by line(not yet)
  3. 3Practisethe path, or the climb(not yet)
  4. 4Revisereviews on schedule(not yet)
Start the lesson
Learn first1D / Fibonacci-style
0%
mastery
0/5 solved
IdeaPracticeTemplatePitfalls

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.

  1. 1Brute force

    Run Dijkstra from every vertex (fine too for sparse graphs).

  2. 2The observation

    Per-source recomputation: one DP over intermediate vertices.

  3. 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

Next · Foundation

Find the City With the Smallest Number of Neighbors at a Threshold Distance

Triple loop with k outermost.

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; putting i or j outside gives wrong distances.
Go deeperresources

Resources

  • Graph Theory playlistWilliam Fiset · video
  • Graph TraversalUSACO Guide · course
  • Disjoint Set Unioncp-algorithms · article
  • Dijkstracp-algorithms · article
  • Topological sortingcp-algorithms · article
  • Shortest paths visualizerVisuAlgo · tool
  • Graph cheatsheetTech Interview Handbook · article
Bellman-FordMinimum Spanning Tree
TodayReviewPatternsProblems

Template · clean C++, Java and Python to revise from

Start the free 7-day trial