Floyd Warshall Algorithm (Multi-source shorted path)

Prashant Mishra - Aug 2 - - Dev Community

Floyd Warshall algorithm
This is bit different from dijikstra's or bellman ford algorithm,
Floyd warshall helps in getting shorted path from all vertices( as source) to all the other vertices in the graph.
It also helps in detecting negative cycle in the graph.
What is shorted path?: Any path that takes least amount of edge weights is called shorted path for the given source and destination node.
Go via every vertex to find the shorted path for the given source and the destination.

//tc : O(n^3) cubic operation, sc : (n^2) for using matrix (since we are using it to store further values 
//while we are solving the prolem, like dp

class Solution
{
    public void shortest_distance(int[][] matrix)
    {
        int n  = matrix.length;
        for(int i =0;i<n;i++){
            for(int j =0;j<n;j++){
                if(matrix[i][j] ==-1){
                    matrix[i][j] = (int)1e9;
                }
                if(i ==j){
                    matrix[i][j] = 0; //disntace of node n from node n will be 0
                }
            }
        }
        for(int k = 0;k<n;k++){
            for(int i =0;i<n;i++){
                for(int j =0;j<n;j++){
                    matrix[i][j] = Integer.min(matrix[i][j], matrix[i][k] + matrix[k][j]);
                }
            }
        }

        // checking for negative edge cycle
        for(int i =0;i<n;i++){
            for(int j =0;j<n;j++){
                if(matrix[i][j] < 0){
                   // it means that the graph has negative edge cycle in it
                }
            }
        }
        for(int i =0;i<n;i++){
            for(int j =0;j<n;j++){
                if(matrix[i][j] ==(int)1e9){
                    matrix[i][j] = -1;
                }
            }
        }

    }
}
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player