Floyd warshall algorithm

Pattern: Shortest paths

medium

For every pair (i, j), allow each vertex k in turn as an intermediate stop: dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]). After all k, every shortest distance is known. -1 means no edge in the input and no path in the output.

The problem

Given an adjacency matrix of a directed graph, where matrix[i][j] is the edge weight or -1 for no edge, change it in place so that each cell holds the shortest distance from i to j, or -1 if there is no path. The tests print the matrix.

Think first

  • What if only vertex 0 may be used as a stop?
  • And then vertices 0 and 1?
  • Why does the order of the loops matter?

Hints

    Brute force, and why it fails

    Run Dijkstra or Bellman-Ford from every vertex: O(V × E log V) or O(V² E).

    The key insight

    Adding one allowed stop at a time builds all-pairs distances in a simple triple loop.

    Dry run

    matrix [[0, 1, 43], [1, 0, 6], [-1, -1, 0]]. With k = 0, nothing improves.

    Step 1 of 3

    The plan

    replace -1 with infinity
    for k: for i: for j: d[i][j] = min(d[i][j], d[i][k] + d[k][j])
    replace infinity with -1
    

    Complexity

    Time
    O(V³)
    Space
    O(1) extra

    Three nested loops over the vertices.

    Edge cases

    • One vertex.
    • No edges: -1 everywhere except the diagonal.
    • Negative edges without negative cycles.
    I've built my logic, show the code

    Java

    class Solution {
        public void shortestDistance(int[][] matrix) {
            int n = matrix.length;
            final int INF = Integer.MAX_VALUE / 2;
            for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if (matrix[i][j] == -1) matrix[i][j] = INF;   // -1: no edge
            for (int k = 0; k < n; k++)             // allow k as a stop on the way, one vertex at a time
                for (int i = 0; i < n; i++)
                    for (int j = 0; j < n; j++)
                        if (matrix[i][k] + matrix[k][j] < matrix[i][j]) matrix[i][j] = matrix[i][k] + matrix[k][j];
            for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if (matrix[i][j] >= INF) matrix[i][j] = -1;
        }
    }

    C++

    class Solution {
    public:
        void shortestDistance(vector<vector<int>>& matrix) {
            int n = static_cast<int>(matrix.size());
            const int INF = INT_MAX / 2;
            for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if (matrix[i][j] == -1) matrix[i][j] = INF;   // -1: no edge
            for (int k = 0; k < n; k++)             // allow k as a stop on the way, one vertex at a time
                for (int i = 0; i < n; i++)
                    for (int j = 0; j < n; j++)
                        if (matrix[i][k] + matrix[k][j] < matrix[i][j]) matrix[i][j] = matrix[i][k] + matrix[k][j];
            for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if (matrix[i][j] >= INF) matrix[i][j] = -1;
        }
    };

    Python

    class Solution:
        def shortestDistance(self, matrix: list[list[int]]) -> None:
            n, INF = len(matrix), float("inf")
            for row in matrix:
                for j in range(n):
                    if row[j] == -1:
                        row[j] = INF                # -1: no edge
            for k in range(n):                      # allow k as a stop on the way, one vertex at a time
                for i in range(n):
                    for j in range(n):
                        if matrix[i][k] + matrix[k][j] < matrix[i][j]:
                            matrix[i][j] = matrix[i][k] + matrix[k][j]
            for row in matrix:
                for j in range(n):
                    if row[j] == INF:
                        row[j] = -1

    Common mistakes

    • Putting k as the inner loop.
    • Adding two infinities and overflowing.

    Similar problems