Network Delay Time LeetCode solution in Java

1
class Solution {
2
HashMap<Integer, HashMap<Integer, Integer>> map = new HashMap<>();
3

4
public int networkDelayTime(int[][] times, int n, int k) {
5
for (int i = 1; i <= n; i++) {
6
map.put(i, new HashMap<>());
7
}
8
for (int i = 0; i < times.length; i++) {
9
map.get(times[i][0]).put(times[i][1], times[i][2]);
10
}
11
int ans = BFS(k, n);
12

13
return ans == 1000 ? -1 : ans;
14
}
15

16
public int BFS(int k, int n) {
17
LinkedList<Integer> queue = new LinkedList<>();
18

19
int[] timeReach = new int[n + 1];
20
Arrays.fill(timeReach, 1000);
21
timeReach[0] = 0;
22

23
timeReach[k] = 0;
24

25
queue.add(k);
26

27
while (!queue.isEmpty()) {
28
int rv = queue.remove();
29
for (int nbrs : map.get(rv).keySet()) {
30
int t = map.get(rv).get(nbrs) + timeReach[rv];
31
if (t < timeReach[nbrs]) {
32
timeReach[nbrs] = t;
33
queue.add(nbrs);
34
}
35
}
36
}
37

38
int time = 0;
39

40
for (int i : timeReach) {
41
time = Math.max(i, time);
42
}
43

44
return time;
45
}
46
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0