forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1462-course-schedule-iv.java
28 lines (26 loc) · 1.08 KB
/
1462-course-schedule-iv.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
class Solution {
public List<Boolean> checkIfPrerequisite(int numCourses, int[][] prerequisites, int[][] queries) {
HashMap<Integer, List<Integer>> hm = new HashMap<>();
List<Boolean> res = new ArrayList<>();
boolean[] visited = new boolean[numCourses];
for (int i = 0; i < prerequisites.length; i++) {
hm.putIfAbsent(prerequisites[i][1], new ArrayList<>());
hm.get(prerequisites[i][1]).add(prerequisites[i][0]);
}
for (int i = 0; i < queries.length; i++) {
visited = new boolean[numCourses];
res.add(dfs(hm, queries[i][1], queries[i][0], visited));
}
return res;
}
boolean dfs(HashMap<Integer, List<Integer>> hm, int s, int target, boolean[] visited) {
if (!hm.containsKey(s)) return false;
if (hm.get(s).contains(target)) return true;
for (int i: hm.get(s)) {
if (visited[i]) continue;
visited[i] = true;
if (dfs(hm, i, target, visited)) return true;
}
return false;
}
}