Course Schedule LeetCode solution in JavaScript

1
var canFinish = function (numCourses, prerequisites) {
2
const adjList = [];
3
const visit = [];
4
construAdj();
5
for (let i = 0; i < numCourses; i++) {
6
if (!dfs(i)) return false;
7
}
8
return true;
9

10
function dfs(i) {
11
// base case
12
if (visit[i]) return false;
13
if (visit[i] === false) return true;
14

15
visit[i] = true;
16

17
for (const nei of adjList[i] ?? []) {
18
if (!dfs(nei)) return false;
19
}
20

21
visit[i] = false;
22
return true;
23
}
24

25
function construAdj() {
26
for (const pre of prerequisites) {
27
if (!adjList[pre[0]]) adjList[pre[0]] = [];
28
adjList[pre[0]].push(pre[1]);
29
}
30
}
31
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0