You are on page 1of 2

//TO IMPLEMENT ALL-PAIRS SHORTEST PATHS ALGORITHM import java.util.

*; class Allpair { public static void main(String ar[]) { int a[][],cost[][]; Scanner st=new Scanner(System.in); System.out.println("Enter the number of vertices"); int n=st.nextInt(); a=new int[n+1][n+1]; cost=new int[n+1][n+1]; System.out.println("Enter the cost if edge exists else enter 1000"); System.out.println("How many edges are present ?"); int e=st.nextInt(); for(int i=1;i<=e;i++) { System.out.println("Enter the end points of edge and its corresponding weight:"); int p,q; p=st.nextInt(); q=st.nextInt(); cost[p][q]=st.nextInt(); } for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) if(i!=j && cost[i][j]==0) cost[i][j]=1000; System.out.println("Original cost Matrix :"); for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) System.out.print(cost[i][j]+" "); System.out.println(); } AllPaths(cost,a,n); System.out.println(); System.out.println("Shortest path Matrix :"); for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) System.out.print(a[i][j]+" "); System.out.println(); } } public static void AllPaths(int cost[][],int a[][],int n) { for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) a[i][j]=cost[i][j];

for(int k=1;k<=n;k++) for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) a[i][j]=Math.min(a[i][j],a[i][k]+a[k][j]); } } /*SAMPLE RUN: E:\>javac AllPair.java E:\>java Allpair Enter the number of vertices 3 Enter the cost if edge exists else enter 1000 How many edges are present ? 5 Enter the end points of edge and its corresponding weight: 124 Enter the end points of edge and its corresponding weight: 216 Enter the end points of edge and its corresponding weight: 232 Enter the end points of edge and its corresponding weight: 1 3 11 Enter the end points of edge and its corresponding weight: 313 Original cost Matrix : 0 4 11 6 0 2 3 1000 0 Shortest path Matrix : 0 4 6 5 0 2 3 7 0 */

You might also like