AlgoLab
AlgorithmsCompare
AlgoLab
AlgorithmsCompareGitHub

© 2026 AlgoLab. Open source.

AlgorithmsGraphsFloyd-Warshall
Graphsintermediateall-pairs-shortest-pathdynamic-programmingdense-graphs

Floyd-Warshall

Floyd-Warshall computes shortest paths between every pair of vertices in a weighted graph. It uses a 3-nested-loop DP: for each intermediate vertex k, update dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]). It runs in O(V³) and handles negative edges (but not negative cycles).

Complexity

Best
O(V³)
Average
O(V³)
Worst
O(V³)
Space
O(V²)

Visualizer

Implementation

void floydWarshall(vector<vector<int>>& dist, int n) {
    for (int k=0;k<n;k++)
        for (int i=0;i<n;i++)
            for (int j=0;j<n;j++)
                if (dist[i][k]+dist[k][j]<dist[i][j])
                    dist[i][j]=dist[i][k]+dist[k][j];
}

How It Works

1.All-Pairs Shortest Path

Unlike Dijkstra (single source), Floyd-Warshall computes shortest paths between every pair of vertices. The result is an n×n matrix where dist[i][j] is the shortest path from i to j.

2.DP Formulation

dist[i][j][k] = shortest path from i to j using only vertices 0..k as intermediates. The recurrence is dist[i][j][k] = min(dist[i][j][k-1], dist[i][k][k-1] + dist[k][j][k-1]). This simplifies to an in-place 2D array.

3.Negative Cycle Detection

After running Floyd-Warshall, if any dist[i][i] < 0, there is a negative cycle reachable from i. The algorithm cannot produce correct results when negative cycles exist.

Related Algorithms

Share2Bellman-FordShare2Dijkstra's AlgorithmShare2Breadth-First Search

Test Your Knowledge

Quiz coming soon for this algorithm.

Back to all algorithms