-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathsolution.java
30 lines (26 loc) · 952 Bytes
/
solution.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
class Solution {
public List<Boolean> checkIfPrerequisite(int numCourses, int[][] prerequisites, int[][] queries) {
// Initialize the graph
boolean[][] graph = new boolean[numCourses][numCourses];
// Build the direct edges from prerequisites
for (int[] edge : prerequisites) {
graph[edge[0]][edge[1]] = true;
}
// Floyd-Warshall to compute transitive closure
for (int k = 0; k < numCourses; k++) {
for (int i = 0; i < numCourses; i++) {
for (int j = 0; j < numCourses; j++) {
if (graph[i][k] && graph[k][j]) {
graph[i][j] = true;
}
}
}
}
// Answer the queries
List<Boolean> result = new ArrayList<>();
for (int[] query : queries) {
result.add(graph[query[0]][query[1]]);
}
return result;
}
}