-
Notifications
You must be signed in to change notification settings - Fork 41
/
solution.ts
34 lines (33 loc) · 914 Bytes
/
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
function canFinish (numCourses: number, prerequisites: number[][]): boolean {
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 visited = new Array<boolean>(numCourses);
const onStack = new Array<boolean>(numCourses);
let result = true;
const dfs = (v:number) => {
if (!result) {
return;
}
onStack[v] = true;
visited[v] = true;
for (const nextV of graph[v]) {
if (!visited[nextV]) {
dfs(nextV);
} else if (onStack[nextV]) {
result = false;
}
}
onStack[v] = false;
};
for (let i = 0; i < numCourses; i++) {
if (!visited[i]) {
dfs(i);
}
}
return result;
}