Floyd Warshall Algorithm (original) (raw)

Given a matrix dist[][] of size **n x n, where dist[i][j] represents the weight of the edge from node i to node j.

Determine the shortest path distance between all pair of nodes in the graph.

**Example:

**Input: dist[][] = [[0, 4, INF, 5, INF],
[INF, 0, 1, INF, 6],
[2, INF, 0, 3, INF],
[INF, INF, 1, 0, 2],
[1, INF, INF, 4, 0]]

5

****Output:**[[0, 4, 5, 5, 7],
[3, 0, 1, 4, 6],
[2, 6, 0, 3, 5],
[3, 7, 1, 0, 2],
[1, 5, 5, 4, 0]]
**Explanation:

25751692

Each cell dist[i][i] in the output shows the shortest distance from node i to node j, computed by considering all possible intermediate nodes using the Floyd-Warshall algorithm.

Floyd Warshall Algorithm:

The Floyd–Warshall algorithm works by maintaining a two-dimensional array that represents the distances between nodes. Initially, this array is filled using only the direct edges between nodes. Then, the algorithm gradually updates these distances by checking if shorter paths exist through intermediate nodes.

This algorithm works for both the **directed and **undirected weighted graphs and can handle graphs with both **positive and **negative weight edges.

**Note: It does not work for the graphs with negative cycles (where the sum of the edges in a cycle is negative).

Idea Behind Floyd Warshall Algorithm:

Suppose we have a graph dist[][] with V vertices from 0 to V-1. Now we have to evaluate a dist[][] where dist[i][j] represents the shortest path between vertex i to j.

Let us assume that vertices i to j have intermediate nodes. The idea behind Floyd Warshall algorithm is to treat each and every vertex k from 0 to V-1 as an intermediate node one by one. When we consider the vertex k, we must have considered vertices from 0 to k-1 already. So we use the shortest paths built by previous vertices to build shorter paths with vertex k included.

The following figure shows the above optimal substructure property in Floyd Warshall algorithm:

1

**Why does Floyd Warshall work?

The algorithm relies on the principle of optimal substructure, meaning:

By the end of the algorithm, all shortest paths are computed optimally because each possible intermediate vertex has been considered.

Why Floyd-Warshall Algorithm better for Dense Graphs and not for Sparse Graphs?

**Dense Graph: A graph in which the number of edges are significantly much higher than the number of vertices.
**Sparse Graph: A graph in which the number of edges are very much low.

No matter how many edges are there in the graph the **Floyd Warshall Algorithm runs for O(V3) times therefore it is best suited for **Dense graphs. In the case of sparse graphs, **Johnson's Algorithm is more suitable.

**Step-by-step implementation

**Illustration:

C++ `

//Driver Code Starts #include #include #include using namespace std;

//Driver Code Ends

void floydWarshall(vector<vector> &dist) { int V = dist.size(); int INF = 1e8;

// for each intermediate vertex
for (int k = 0; k < V; k++) {

    // Pick all vertices as source one by one
    for (int i = 0; i < V; i++) {

        // Pick all vertices as destination
        // for the above picked source
        for (int j = 0; j < V; j++) {

            // shortest path from i to j 
            if(dist[i][k] != INF && dist[k][j]!= INF )
                dist[i][j] = min(dist[i][j],
                                 dist[i][k] + dist[k][j]);
        }
    }
}

}

//Driver Code Starts

int main() { int INF = 1e8; vector<vector> dist = {{0, 4, INF, 5, INF}, {INF, 0, 1, INF, 6}, {2, INF, 0, 3, INF}, {INF, INF, 1, 0, 2}, {1, INF, INF, 4, 0}};

floydWarshall(dist);

for(int i = 0; i < dist.size(); i++) {
    for(int j = 0; j < dist.size(); j++) {
        cout<<dist[i][j]<<" ";
    }
    cout<<endl;
}
return 0;

} //Driver Code Ends

Java

//Driver Code Starts class GFG { //Driver Code Ends

static void floydWarshall(int[][] dist) {
    int V = dist.length;
    int INF = (int)1e8;

    // for each intermediate vertex
    // between source and destination
    for (int k = 0; k < V; k++) {

        // Pick all vertices as source one by one
        for (int i = 0; i < V; i++) {

            // Pick all vertices as destination
            // for the above picked source
            for (int j = 0; j < V; j++) {

                // shortest path from i to j 
                if(dist[i][k] != INF && dist[k][j]!= INF) 
                    dist[i][j] = Math.min(dist[i][j], 
                                          dist[i][k] + dist[k][j]);
            }
        }
    }
}

//Driver Code Starts

public static void main(String[] args) {
    int INF = (int)1e8;
    
    int[][] dist = {{0, 4, INF, 5, INF},
                    {INF, 0, 1, INF, 6},
                    {2, INF, 0, 3, INF },
                    {INF, INF, 1, 0, 2},
                    {1, INF, INF, 4, 0}};

    floydWarshall(dist);
    
    for (int i = 0; i < dist.length; i++) {
        for (int j = 0; j < dist.length; j++) {
            System.out.print(dist[i][j] + " ");
        }
        System.out.println();
    }
}

} //Driver Code Ends

Python

def floydWarshall(dist): V = len(dist) INF = int(1e8)

# for each intermediate vertex
for k in range(V):

    # Pick all vertices as source one by one
    for i in range(V):

        # Pick all vertices as destination
        # for the above picked source
        for j in range(V):

            # shortest path from i to j 
            if dist[i][k] != INF and dist[k][j] != INF:
                dist[i][j] = min(dist[i][j],
                                 dist[i][k] + dist[k][j])

#Driver Code Starts if name == "main": INF = int(1e8) dist = [[0, 4, INF, 5, INF], [INF, 0, 1, INF, 6], [2, INF, 0, 3, INF], [INF, INF, 1, 0, 2], [1, INF, INF, 4, 0]]

floydWarshall(dist)

for row in dist:
    print(*row)

#Driver Code Ends

C#

//Driver Code Starts using System; using System.Collections.Generic;

class GFG {

//Driver Code Ends

public static void floydWarshall(List<List<int>> dist) {
    int V = dist.Count;
    int INF = 100000000;

    // for each intermediate vertex
    for (int k = 0; k < V; k++) {

        // Pick all vertices as source one by one
        for (int i = 0; i < V; i++) {

            // Pick all vertices as destination
            // for the above picked source
            for (int j = 0; j < V; j++) {

                // shortest path from i to j 
                if (dist[i][k] != INF && dist[k][j] != INF)
                    dist[i][j] = Math.Min(dist[i][j],
                                          dist[i][k] + dist[k][j]);
            }
        }
    }
}

//Driver Code Starts

public static void Main() {
    int INF = 100000000;

    List<List<int>> dist = new List<List<int>>() {
        new List<int>{0, 4, INF, 5, INF},
        new List<int>{INF, 0, 1, INF, 6},
        new List<int>{2, INF, 0, 3, INF},
        new List<int>{INF, INF, 1, 0, 2},
        new List<int>{1, INF, INF, 4, 0}
    };

    floydWarshall(dist);

    for (int i = 0; i < dist.Count; i++) {
        for (int j = 0; j < dist.Count; j++) {
            Console.Write(dist[i][j] + " ");
        }
        Console.WriteLine();
    }
}

}

//Driver Code Ends

JavaScript

function floydWarshall(dist) { let V = dist.length; let INF = 1e8;

// for each intermediate vertex
for (let k = 0; k < V; k++) {

    // Pick all vertices as source one by one
    for (let i = 0; i < V; i++) {

        // Pick all vertices as destination
        // for the above picked source
        for (let j = 0; j < V; j++) {

            // shortest path from i to j 
            if (dist[i][k] !== INF && dist[k][j] !== INF)
                dist[i][j] = Math.min(dist[i][j],
                                       dist[i][k] + dist[k][j]);
        }
    }
}

}

//Driver Code Starts // Driver code let INF = 1e8; let dist = [ [0, 4, INF, 5, INF], [INF, 0, 1, INF, 6], [2, INF, 0, 3, INF], [INF, INF, 1, 0, 2], [1, INF, INF, 4, 0] ];

floydWarshall(dist);

for (let i = 0; i < dist.length; i++) { let row = ""; for (let j = 0; j < dist.length; j++) { row += dist[i][j] + " "; } console.log(row); }

//Driver Code Ends

`

Output

0 4 5 5 7 3 0 1 4 6 2 6 0 3 5 3 7 1 0 2 1 5 5 4 0

**Time Complexity: O(V3), where V is the number of vertices in the graph and we run three nested loops each of size V.
**Auxiliary Space: O(1).

Read here for detailed analysis: complexity analysis of the Floyd Warshall algorithm

Real World Applications of Floyd-Warshall Algorithm

Problems based on Shortest Path