Program – 7 From a given vertex in a weighted connected graph, find shortest paths to other vertices using Dijkstra's algorithm. Write the program in Java. import java.util.Scanner; public class DijkstrasClass { final static int MAX = 20; final static int infinity = 999; static int n; // No. of vertices of G static int a[ ][ ]; // Cost matrix static Scanner scan = new Scanner(System.in); public static void main(String[ ] args) { ReadMatrix( ); int s = 0; // starting vertex System.out.println("Enter starting vertex: "); s = scan.nextInt( ); //starting vertex s=1 Dijkstras(s); } // find shortest path 4 2 static void ReadMatrix( ) 3 2 1 { 3 4 7 6 5 5 4 a = new int[MAX][MAX]; System.out.println("Enter the number of vertices:"); n = scan.nextInt( ); //n=5 System.out.println("Enter the cost adjacency matrix:"); for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) 1 2 3 1 0 3 999 7 999 2 3 0 4 2 999 999 4 0 5 6 4 7 5 0 4 5 999 999 6 4 0 a[i][j] = scan.nextInt( ); 3 } 2 4 5 static void Dijkstras(int s) { int S[ ] = new int[MAX]; // to store visited vertex int d[ ] = new int[MAX]; //to store distance from source vertex int u, v; S[i] 1 2 3 4 5 int i; 0 0 0 0 0 for (i = 1; i <= n; i++) { d[i] 1 2 3 4 5 S[i] = 0; 0 3 999 7 999 d[i] = a[s][i]; S[i] 1 2 3 4 5 } 1 0 0 0 0 S[s] = 1; d[s] = 1; d[i] 1 2 3 4 5 1 3 999 7 999 S[i] i = 2; while (i <= n) 1 2 3 4 5 1 1 0 0 0 { u = Extract_Min(S, d); // u=2 S[u] = 1; //S[2]=1 i++; //i=3 for (v = 1; v <= n; v++) { if (((d[u] + a[u][v] < d[v]) && (S[v] == 0))) d[v] = d[u] + a[u][v]; } } if (i != s) System.out.println(i + ":" + d[i]); } //end of Dijkstras(s); d[i] 1 2 3 4 1 3 999 7 7 5 5 999 V=1 if (((d[2] + a[2][1] < d[1]) && (S[1] == 0))) if (((3 + 3 < 1) && (1 == 0))) F V=2 if (((d[2] + a[2][2] < d[2]) && (S[2] == 0))) if (((3 + 0 < 3) && (1 == 0))) F V=3 if (((d[2] + a[2][3] < d[3]) && (S[3] == 0))) if (((3 + 4 < 999) && (0 == 0)))T d[v] = d[u] + a[u][v]; d[3] = d[2] + a[2][3];=3+4=7 V=4 if (((d[2] + a[2][4] < d[4]) && (S[4] == 0))) if (((3 + 2 < 7) && (0 == 0)))T d[v] = d[u] + a[u][v]; d[4] = d[2] + a[2][4];=3+2=5 V=5 if (((d[2] + a[2][5] < d[5]) && (S[5] == 0))) if (((3 + 999 < 999) && (0 == 0))) F static int Extract_Min(int S[ ], int d[ ]) { int i, j = 1, min; min = infinity; //min=999; for (i = 1; i <= n; i++) { if ((d[i] < min) && (S[i] == 0)) { min = d[i]; j = i; } } return (j); //return(2) } } //class i=1 If(1<999) && S[1]==0) F i=2 if(3<999) && S[2]==0) T min=3 j=i (ie., j=2) i=3 if(999<3) && S[3]==0) F i=4 if(7<3) && S[4]==0) F i=5 if(999<3) && S[5]==0) F S[i] 1 2 3 4 5 1 0 0 0 0 d[i] 1 2 3 4 1 3 999 7 5 999 4 b 3 a Tree vertices a(-,0) 7 2 c 5 d d 6 4 e Remaining vertices b(a,3) c(-,∞) d(a,7) e(-,∞) 3 a b(a,3) 2 c(b,3+4) d(b,3+2) e(-,∞) c(b,7) e(d,5+4) 3 a c(b,7) e(d,9) 1 e(d,9) 2 7 6 5 e 4 4 2 e c d 7 6 4 4 2 3 c d b e 4 5 2 7 6 5 4 b 3 c d 7 a d(b,5) 4 b 3 6 5 4 5 4 8