- Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_3241.java
64 lines (61 loc) · 2.52 KB
/
_3241.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
packagecom.fishercoder.solutions.fourththousand;
importjava.util.ArrayList;
importjava.util.Arrays;
importjava.util.List;
importjava.util.PriorityQueue;
publicclass_3241 {
publicstaticclassSolution1 {
/*
* This is my original solution during the contest, it's correct but not efficient enough, so got TLE on LeetCode.
* TODO: figure out a more efficient approach.
*/
publicint[] timeTaken(int[][] edges) {
int[] times = newint[edges.length + 1];
List<Integer>[] graph = newArrayList[edges.length + 1];
for (inti = 0; i < edges.length + 1; i++) {
graph[i] = newArrayList<>();
}
for (int[] edge : edges) {
graph[edge[0]].add(edge[1]);
graph[edge[1]].add(edge[0]);
}
for (inti = 0; i < edges.length + 1; i++) {
times[i] = markAllNodes(graph, i);
}
returntimes;
}
privateintmarkAllNodes(List<Integer>[] graph, intstartNode) {
PriorityQueue<int[]> q = newPriorityQueue<>((a, b) -> a[1] - b[1]);
q.offer(newint[] {startNode, 0});
int[] shortestTime = newint[graph.length];
Arrays.fill(shortestTime, Integer.MAX_VALUE);
shortestTime[startNode] = 0;
intmaxTime = -1;
while (!q.isEmpty()) {
int[] curr = q.poll();
intcurrNode = curr[0];
intcurrTime = curr[1];
if (currTime > shortestTime[currNode]) {
continue;
}
maxTime = shortestTime[currNode];
for (intneighbor : graph[currNode]) {
if (neighbor % 2 == 0) {
if (currTime + 2 < shortestTime[neighbor]) {
shortestTime[neighbor] = currTime + 2;
maxTime = Math.max(maxTime, shortestTime[neighbor]);
q.offer(newint[] {neighbor, shortestTime[neighbor]});
}
} else {
if (currTime + 1 < shortestTime[neighbor]) {
shortestTime[neighbor] = currTime + 1;
maxTime = Math.max(maxTime, shortestTime[neighbor]);
q.offer(newint[] {neighbor, shortestTime[neighbor]});
}
}
}
}
returnmaxTime;
}
}
}