forked from luliyucoordinate/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0210.js
More file actions
32 lines (30 loc) · 739 Bytes
/
0210.js
File metadata and controls
32 lines (30 loc) · 739 Bytes
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
var findOrder = function(n, prerequisites) {
let g = {};
let d = new Array(n), vis = new Array(n), res = [], q = [];
d.fill(0); vis.fill(0);
for (let it of prerequisites) {
if (g[it[1]])
g[it[1]].push(it[0]);
else g[it[1]] = [it[0]];
d[it[0]]++;
}
for (let i = 0; i < n; i++) {
if (d[i] == 0) {
q.push(i);
vis[i] = 1;
}
}
while (q.length) {
let cur = q.shift();
res.push(cur);
n--;
for (let i of g[cur] || []) {
d[i]--;
if (!vis[i] && d[i] == 0) {
vis[i] = 1;
q.push(i);
}
}
}
return n == 0 ? res : [];
};