-
Notifications
You must be signed in to change notification settings - Fork 41
/
solution.ts
40 lines (38 loc) · 1.05 KB
/
solution.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
29
30
31
32
33
34
35
36
37
38
39
40
function findOrder (numCourses: number, prerequisites: number[][]): number[] {
const graph = new Array<number[]>(numCourses);
for (let i = 0; i < numCourses; i++) {
graph[i] = [];
}
for (const [to, from, ] of prerequisites) {
graph[from].push(to);
}
const onStack = new Array<boolean>(numCourses).fill(false);
const visited = new Array<boolean>(numCourses).fill(false);
let hasCircle = false;
const post:number[] = [];
const dfs = (v:number) => {
visited[v] = true;
onStack[v] = true;
for (const nextV of graph[v]) {
if (hasCircle) {
break;
}
if (!visited[nextV]) {
dfs(nextV);
} else if (onStack[nextV]) {
hasCircle = true;
}
}
onStack[v] = false;
post.push(v);
};
for (let i = 0; i < numCourses; i++) {
if (!visited[i] && !hasCircle) {
dfs(i);
}
}
if (hasCircle) {
return [];
}
return post.reverse();
}