forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution2.ts
28 lines (28 loc) · 846 Bytes
/
Solution2.ts
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
function checkIfPrerequisite(n: number, prerequisites: number[][], queries: number[][]): boolean[] {
const f = Array.from({ length: n }, () => Array(n).fill(false));
const g: number[][] = Array.from({ length: n }, () => []);
const indeg: number[] = Array(n).fill(0);
for (const [a, b] of prerequisites) {
g[a].push(b);
++indeg[b];
}
const q: number[] = [];
for (let i = 0; i < n; ++i) {
if (indeg[i] === 0) {
q.push(i);
}
}
while (q.length) {
const i = q.shift()!;
for (const j of g[i]) {
f[i][j] = true;
for (let h = 0; h < n; ++h) {
f[h][j] ||= f[h][i];
}
if (--indeg[j] === 0) {
q.push(j);
}
}
}
return queries.map(([a, b]) => f[a][b]);
}