We are given a directed graph and if we need to find out minimum distance between all the sources and destinations, we will use Floyd Warshall All Pair Shortest Path Algorithm.
Suppose we are given below graph
Suppose we are given below graph
import java.util.*; import java.lang.*; public class Floyd { final static int INF=Integer.MAX_VALUE; void Path(int graph[][],int n) { int minDistance[][]=new int[n][n]; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { minDistance[i][j]=graph[i][j]; } } for(int k=0;k<n;k++) { minDistance[k][k]=0; } for(int k=0;k<n;k++) { for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(minDistance[i][j]>minDistance[i][k]+minDistance[k][j] && minDistance[i][k] !=INF && minDistance[k][j]!=INF) minDistance[i][j]=minDistance[i][k]+minDistance[k][j]; } } } printMatrix(minDistance,n); } void printMatrix(int minDistance[][],int n) { for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { System.out.print(minDistance[i][j]+ " "); } System.out.println(); } } public static void main(String[] args) { int a[][]={{0,5,INF,10}, {INF,0,3,INF}, {INF,INF,0,1}, {INF,INF,INF,0}}; Floyd f=new Floyd(); f.Path(a,4); } }