forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0207-course-schedule.ts
49 lines (42 loc) · 1.11 KB
/
0207-course-schedule.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
41
42
43
44
45
46
47
48
49
function canFinish(numCourses: number, prerequisites: number[][]): boolean {
const graph = createGraph(numCourses, prerequisites);
let seen = new Set();
let seeing = new Set();
function explore(course: number): boolean {
if (seen.has(course)) {
return true;
}
if (seeing.has(course)) {
return false;
}
seeing.add(course);
for (let neighbor of graph[course]) {
if (!explore(neighbor)) {
return false;
}
}
seen.add(course);
seeing.delete(course);
return true;
}
for (let i = 0; i < numCourses; i++) {
if (!explore(i)) {
return false;
}
}
return true;
}
function createGraph(numCourses: number, edges: number[][]): number[][] {
const graph = Array.from({ length: numCourses }, () => []);
for (let edge of edges) {
let [a, b] = edge;
if (!(a in graph)) {
graph[a] = [];
}
if (!(b in graph)) {
graph[b] = [];
}
graph[a].push(b);
}
return graph;
}