1
1
package com .thealgorithms .datastructures .graphs ;
2
2
3
3
import java .util .Arrays ;
4
+ import java .util .Set ;
5
+ import java .util .TreeSet ;
6
+ import org .apache .commons .lang3 .tuple .Pair ;
4
7
5
8
/**
6
9
* Dijkstra's algorithm for finding the shortest path from a single source vertex to all other vertices in a graph.
@@ -36,18 +39,24 @@ public int[] run(int[][] graph, int source) {
36
39
37
40
int [] distances = new int [vertexCount ];
38
41
boolean [] processed = new boolean [vertexCount ];
42
+ Set <Pair <Integer , Integer >> unprocessed = new TreeSet <>();
39
43
40
44
Arrays .fill (distances , Integer .MAX_VALUE );
41
45
Arrays .fill (processed , false );
42
46
distances [source ] = 0 ;
47
+ unprocessed .add (Pair .of (0 , source ));
43
48
44
- for (int count = 0 ; count < vertexCount - 1 ; count ++) {
45
- int u = getMinDistanceVertex (distances , processed );
49
+ while (!unprocessed .isEmpty ()) {
50
+ Pair <Integer , Integer > distanceAndU = unprocessed .iterator ().next ();
51
+ unprocessed .remove (distanceAndU );
52
+ int u = distanceAndU .getRight ();
46
53
processed [u ] = true ;
47
54
48
55
for (int v = 0 ; v < vertexCount ; v ++) {
49
56
if (!processed [v ] && graph [u ][v ] != 0 && distances [u ] != Integer .MAX_VALUE && distances [u ] + graph [u ][v ] < distances [v ]) {
57
+ unprocessed .remove (Pair .of (distances [v ], v ));
50
58
distances [v ] = distances [u ] + graph [u ][v ];
59
+ unprocessed .add (Pair .of (distances [v ], v ));
51
60
}
52
61
}
53
62
}
@@ -56,27 +65,6 @@ public int[] run(int[][] graph, int source) {
56
65
return distances ;
57
66
}
58
67
59
- /**
60
- * Finds the vertex with the minimum distance value from the set of vertices that have not yet been processed.
61
- *
62
- * @param distances The array of current shortest distances from the source vertex.
63
- * @param processed The array indicating whether each vertex has been processed.
64
- * @return The index of the vertex with the minimum distance value.
65
- */
66
- private int getMinDistanceVertex (int [] distances , boolean [] processed ) {
67
- int min = Integer .MAX_VALUE ;
68
- int minIndex = -1 ;
69
-
70
- for (int v = 0 ; v < vertexCount ; v ++) {
71
- if (!processed [v ] && distances [v ] <= min ) {
72
- min = distances [v ];
73
- minIndex = v ;
74
- }
75
- }
76
-
77
- return minIndex ;
78
- }
79
-
80
68
/**
81
69
* Prints the shortest distances from the source vertex to all other vertices.
82
70
*
0 commit comments