-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetworkTimeDelay.java
More file actions
58 lines (43 loc) · 1.37 KB
/
NetworkTimeDelay.java
File metadata and controls
58 lines (43 loc) · 1.37 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package graph;
import java.util.*;
public class NetworkTimeDelay {
public static int networkDelayTime(int[][] times, int n, int k) {
// Creating Graph.
List<Node>[] graph = new List[n];
for (int i = 0; i < n; i++) {
graph[i] = new ArrayList<>();
}
// Initializing Graph.
for (int[] t : times) {
graph[t[0] - 1].add(new Node(t[1] - 1, t[2]));
}
int[] time = new int[n];
Arrays.fill(time, Integer.MAX_VALUE);
time[--k] = 0;
boolean[] isVisited = new boolean[n];
Queue<Integer> q = new ArrayDeque<>();
q.offer(k);
while (!q.isEmpty()) {
int curr = q.poll();
isVisited[curr] = false;
for (var next : graph[curr]) {
if (time[curr] + next.time < time[next.dest]) {
time[next.dest] = time[curr] + next.time;
if (!isVisited[next.dest]) {
q.offer(next.dest);
isVisited[next.dest] = true;
}
}
}
}
int res = time[0];
for (var t : time)
if (t == Integer.MAX_VALUE) return -1;
else if (t > res) res = t;
return res;
}
public static void main(String[] args) {
}
record Node(int dest, int time) {
}
}