-
-
Notifications
You must be signed in to change notification settings - Fork 9k
/
Copy pathSolution2.java
34 lines (33 loc) · 1.03 KB
/
Solution2.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
private static final int INF = 0x3f3f;
public int networkDelayTime(int[][] times, int n, int k) {
List<int[]>[] g = new List[n];
int[] dist = new int[n];
for (int i = 0; i < n; ++i) {
dist[i] = INF;
g[i] = new ArrayList<>();
}
for (int[] t : times) {
g[t[0] - 1].add(new int[] {t[1] - 1, t[2]});
}
dist[k - 1] = 0;
PriorityQueue<int[]> q = new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));
q.offer(new int[] {0, k - 1});
while (!q.isEmpty()) {
int[] p = q.poll();
int u = p[1];
for (int[] ne : g[u]) {
int v = ne[0], w = ne[1];
if (dist[v] > dist[u] + w) {
dist[v] = dist[u] + w;
q.offer(new int[] {dist[v], v});
}
}
}
int ans = 0;
for (int d : dist) {
ans = Math.max(ans, d);
}
return ans == INF ? -1 : ans;
}
}