Skip to content

Commit 6576314

Browse files
committed
Speed up DijkstraAlgorithm
1 parent b971453 commit 6576314

File tree

1 file changed

+11
-23
lines changed

1 file changed

+11
-23
lines changed

src/main/java/com/thealgorithms/datastructures/graphs/DijkstraAlgorithm.java

Lines changed: 11 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
package com.thealgorithms.datastructures.graphs;
22

33
import java.util.Arrays;
4+
import java.util.Set;
5+
import java.util.TreeSet;
6+
import org.apache.commons.lang3.tuple.Pair;
47

58
/**
69
* 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) {
3639

3740
int[] distances = new int[vertexCount];
3841
boolean[] processed = new boolean[vertexCount];
42+
Set<Pair<Integer, Integer>> unprocessed = new TreeSet<>();
3943

4044
Arrays.fill(distances, Integer.MAX_VALUE);
4145
Arrays.fill(processed, false);
4246
distances[source] = 0;
47+
unprocessed.add(Pair.of(0, source));
4348

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();
4653
processed[u] = true;
4754

4855
for (int v = 0; v < vertexCount; v++) {
4956
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));
5058
distances[v] = distances[u] + graph[u][v];
59+
unprocessed.add(Pair.of(distances[v], v));
5160
}
5261
}
5362
}
@@ -56,27 +65,6 @@ public int[] run(int[][] graph, int source) {
5665
return distances;
5766
}
5867

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-
8068
/**
8169
* Prints the shortest distances from the source vertex to all other vertices.
8270
*

0 commit comments

Comments
 (0)