Skip to content

Commit 02f4f23

Browse files
Add Dijkstra algorithm implementation (Fixes #7112)
1 parent bf8b2d3 commit 02f4f23

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

graphs/Dijkstra.java

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package com.thealgorithms.graphs;
2+
3+
import java.util.*;
4+
5+
public class Dijkstra {
6+
7+
public static int[] dijkstra(List<List<int[]>> graph, int source) {
8+
int n = graph.size();
9+
int[] dist = new int[n];
10+
Arrays.fill(dist, Integer.MAX_VALUE);
11+
dist[source] = 0;
12+
13+
PriorityQueue<int[]> pq =
14+
new PriorityQueue<>(Comparator.comparingInt(a -> a[1]));
15+
16+
pq.offer(new int[]{source, 0});
17+
18+
while (!pq.isEmpty()) {
19+
int[] curr = pq.poll();
20+
int u = curr[0];
21+
int d = curr[1];
22+
23+
if (d > dist[u]) continue;
24+
25+
for (int[] edge : graph.get(u)) {
26+
int v = edge[0];
27+
int w = edge[1];
28+
29+
if (w < 0) {
30+
throw new IllegalArgumentException("Negative weight detected");
31+
}
32+
33+
if (dist[u] + w < dist[v]) {
34+
dist[v] = dist[u] + w;
35+
pq.offer(new int[]{v, dist[v]});
36+
}
37+
}
38+
}
39+
return dist;
40+
}
41+
}

0 commit comments

Comments
 (0)