- Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_1462.java
54 lines (50 loc) · 1.79 KB
/
_1462.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
packagecom.fishercoder.solutions.secondthousand;
importjava.util.ArrayList;
importjava.util.HashMap;
importjava.util.List;
importjava.util.Map;
publicclass_1462 {
publicstaticclassSolution1 {
/*
* My completely original solution.
* DFS + part of topological sort (building the adjacency list)
*/
publicList<Boolean> checkIfPrerequisite(
intnumCourses, int[][] prerequisites, int[][] queries) {
List<Integer>[] graph = newArrayList[numCourses];
for (inti = 0; i < numCourses; i++) {
graph[i] = newArrayList<>();
}
for (int[] pre : prerequisites) {
graph[pre[0]].add(pre[1]);
}
List<Boolean> result = newArrayList<>();
// this cache is essential to speed things up, otherwise TLE on LeetCode
Map<String, Boolean> cache = newHashMap<>();
for (int[] query : queries) {
result.add(isPrereq(query[0], query[1], graph, cache));
}
returnresult;
}
privateBooleanisPrereq(
intpre, inttarget, List<Integer>[] graph, Map<String, Boolean> cache) {
if (pre == target) {
cache.put(pre + "-" + target, true);
returntrue;
}
if (cache.containsKey(pre + "-" + target)) {
returncache.get(pre + "-" + target);
}
for (intv : graph[pre]) {
if (isPrereq(v, target, graph, cache)) {
returntrue;
}
}
cache.put(pre + "-" + target, false);
returnfalse;
}
}
publicstaticclassSolution2 {
/*TODO: use BFS to solve this problem.*/
}
}