1+ // Dijkstra's Algorithm in Java
2+
3+ public class DijkstraAlgorithm {
4+
5+ public static void dijkstra (int [][] graph , int source ) {
6+ int count = graph .length ;
7+ boolean [] visitedVertex = new boolean [count ];
8+ int [] distance = new int [count ];
9+ for (int i = 0 ; i < count ; i ++) {
10+ visitedVertex [i ] = false ;
11+ distance [i ] = Integer .MAX_VALUE ;
12+ }
13+
14+ // Distance of self loop is zero
15+ distance [source ] = 0 ;
16+ for (int i = 0 ; i < count ; i ++) {
17+
18+ // Update the distance between neighbouring vertex and source vertex
19+ int u = findMinDistance (distance , visitedVertex );
20+ visitedVertex [u ] = true ;
21+
22+ // Update all the neighbouring vertex distances
23+ for (int v = 0 ; v < count ; v ++) {
24+ if (!visitedVertex [v ] && graph [u ][v ] != 0 && (distance [u ] + graph [u ][v ] < distance [v ])) {
25+ distance [v ] = distance [u ] + graph [u ][v ];
26+ }
27+ }
28+ }
29+ for (int i = 0 ; i < distance .length ; i ++) {
30+ System .out .println (String .format ("Distance from %s to %s is %s" , source , i , distance [i ]));
31+ }
32+
33+ }
34+
35+ // Finding the minimum distance
36+ private static int findMinDistance (int [] distance , boolean [] visitedVertex ) {
37+ int minDistance = Integer .MAX_VALUE ;
38+ int minDistanceVertex = -1 ;
39+ for (int i = 0 ; i < distance .length ; i ++) {
40+ if (!visitedVertex [i ] && distance [i ] < minDistance ) {
41+ minDistance = distance [i ];
42+ minDistanceVertex = i ;
43+ }
44+ }
45+ return minDistanceVertex ;
46+ }
47+
48+ public static void main (String [] args ) {
49+ int graph [][] = new int [][] {
50+ { 0 , 0 , 1 , 2 , 0 , 0 , 0 },
51+ { 0 , 0 , 2 , 0 , 0 , 3 , 0 },
52+ { 1 , 2 , 0 , 1 , 3 , 0 , 0 },
53+ { 2 , 0 , 1 , 0 , 0 , 0 , 1 },
54+ { 0 , 0 , 3 , 0 , 0 , 2 , 0 },
55+ { 0 , 3 , 0 , 0 , 2 , 0 , 1 },
56+ { 0 , 0 , 0 , 1 , 0 , 1 , 0 }
57+ };
58+
59+ DijkstraAlgorithm T = new DijkstraAlgorithm ();
60+
61+ T .dijkstra (graph , 0 );
62+ }
63+ }
64+
65+
66+
67+
68+
69+
70+
71+
72+
73+
74+
75+ /*
76+
77+ EXPLANATION: (Pseudo Code)
78+
79+ function dijkstra(G, S)
80+ for each vertex V in G
81+ distance[V] <- infinite
82+ previous[V] <- NULL
83+ If V != S, add V to Priority Queue Q
84+ distance[S] <- 0
85+
86+ while Q IS NOT EMPTY
87+ U <- Extract MIN from Q
88+ for each unvisited neighbour V of U
89+ tempDistance <- distance[U] + edge_weight(U, V)
90+ if tempDistance < distance[V]
91+ distance[V] <- tempDistance
92+ previous[V] <- U
93+ return distance[], previous[]
94+
95+ */
0 commit comments