import java.util.*;
class Graph
{
int g[][];
int v,e;
int visited[] , x[] , n;
void creategraph()
{
int a,b,w;
Scanner kbd = new Scanner(System.in);
System.out.print("Enter number of vertices ");
v = kbd.nextInt();
System.out.print("Enter number of edges ");
e = kbd.nextInt();
//create matrix of v+1 rows and v+1 cols
g = new int[v+1][v+1];
//initialize entire matrix g to infinity
for(int i = 1 ; i <= v; i++)
for(int j = 1 ; j <= v ; j++)
g[i][j] = 32767;
//initialze diagonal elements to zero
for (int i = 1 ; i <= v ; i++)
g[i][i] = 0;
//store edge information
for (int i = 1; i<= e ; i++)
{
System.out.print("Enter edge information ");
a = kbd.nextInt();
b = kbd.nextInt();
System.out.print("Enter weight ");
w = kbd.nextInt();
g[a][b] = w;
}
} // end creategraph
void allpair()
{
for (int k = 1 ; k <= v ; k++)
for (int i = 1 ; i <= v ; i++)
for (int j = 1 ; j <= v ; j++)
g[i][j] = Math.min(g[i][j] , g[i][k] + g[k][j]);
//print solution in tabular format
System.out.println("Shortest distance ");
System.out.println("From\t\t to");
for (int i=1 ; i<=v ; i++)
for (int j=1 ; j<=v ; j++)
System.out.println(i + "\t\t\t\t " + j + " = " + g[i][j]);
}
} //end Graph class
public class AllPair
{
public static void main(String args[])
{
Graph g = new Graph();
g.creategraph();
g.allpair();
}
}
/*Output:
Enter number of vertices 4
Enter number of edges 7
Enter edge information 1
2
Enter weight 21
Enter edge information 1
4
Enter weight 8
Enter edge information 3
1
Enter weight 3
Enter edge information 2
1
Enter weight 2
Enter edge information 4
2
Enter weight 2
Enter edge information 4
3
Enter weight 18
Enter edge information 2
3
Enter weight 3
Shortest distance
From to
1 1 = 0
1 2 = 10
1 3 = 13
1 4 = 8
2 1 = 2
2 2 = 0
2 3 = 3
2 4 = 10
3 1 = 3
3 2 = 13
3 3 = 0
3 4 = 11
4 1 = 4
4 2 = 2
4 3 = 5
4 4 = 0
*/
0 comments:
Post a Comment