-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1462. Course schedule IV
53 lines (42 loc) · 1.38 KB
/
1462. Course schedule IV
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
//1462. Course schedule IV
class Solution {
public List<Boolean> checkIfPrerequisite(int numCourses, int[][] prerequisites, int[][] queries) {
List<Integer>[] adj = new ArrayList[numCourses];
boolean[][] prereq = new boolean[numCourses][numCourses];
int[] inDegree = new int[numCourses];
for(int i = 0; i < numCourses; i++) {
adj[i] = new ArrayList<>();
}
for(int[] edge : prerequisites) {
int a = edge[0], b = edge[1];
adj[a].add(b);
prereq[b][a] = true;
inDegree[b]++;
}
Queue<Integer> q = new LinkedList<>();
for(int i = 0; i < numCourses; i++) {
if(inDegree[i] == 0) {
q.add(i);
}
}
while(!q.isEmpty()) {
int u = q.poll();
for(int v : adj[u]) {
for(int i = 0; i < numCourses; i++) {
if(prereq[u][i]) {
prereq[v][i] = true;
}
}
if(--inDegree[v] == 0) {
q.add(v);
}
}
}
List<Boolean> ans = new ArrayList<>();
for(int[] query : queries) {
int u = query[0], v = query[1];
ans.add(prereq[v][u]);
}
return ans;
}
}