DSA
    advanced

    Floyd-Warshall Algorithm

    Software Engineer path · lesson 26 of 99
    time O(V³)
    space O(V²)

    Directed and weighted. Keep it to 6 nodes or fewer so the matrix stays readable.

    Try:
    317241ABCD
    ABCDABCD037∞∞01∞2∞04∞1∞0
    k (via)i → j celld[i][k], d[k][j]Improved

    Start with direct edge weights; ∞ where there is no edge.

    Code (running line highlighted)
    1. 1d[i][j] = w(i, j), d[i][i] = 0, else ∞
    2. 2for k in nodes:
    3. 3 for i in nodes:
    4. 4 for j in nodes:
    5. 5 if d[i][k] + d[k][j] < d[i][j]: d[i][j] = d[i][k] + d[k][j]
    Checks
    0 / 15
    Improvements
    0 / 7

    Tap any element in the diagram to inspect its state at this step.

    1 / 21

    Keys: ← → step, Space play/pause. Predict mode pauses before key steps and asks what happens next.

    All pairs, one vertex at a time

    Sequence

    Order how Floyd-Warshall fills the distance matrix.

    Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.

    1. 1Drop a step here
    2. 2Drop a step here
    3. 3Drop a step here
    4. 4Drop a step here
    5. 5Drop a step here
    5 pieces left to place

    Test your knowledge

    20 questions
    Question 1 of 20
    Score: 0

    What is the recurrence relation in Floyd-Warshall?

    The short version

    Imagine finding shortcuts between cities. For each intermediate city K, you check: 'Is going through K faster than the direct route?' You do this for EVERY pair of cities, considering EVERY possible intermediate stop.

    In more depth

    The Triple Loop

    for k in 0..n:
        for i in 0..n:
            for j in 0..n:
                dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])

    Key Insight

    The outermost loop (k) represents: "Consider paths that go through nodes 0, 1, ..., k"

    Use Cases

    Small, dense graphs
    Need ALL shortest paths (not just from one source)
    Transitive closure (reachability)

    When to reach for this

    • Need shortest path between ALL pairs
    • Graph is small (V ≤ 400)
    • Graph is dense (many edges)
    • Transitive closure queries

    Interview Questions

    Google
    Uber
    LinkedIn
    Microsoft
    Palantir
    Amazon
    Google
    Meta
    Bloomberg
    Bloomberg
    Netflix
    Amazon
    Palantir
    LinkedIn
    Microsoft

    Love this visualization?

    Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.

    100% free • No credit card required