-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Copy path207-canFinish.js
38 lines (30 loc) · 894 Bytes
/
207-canFinish.js
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
function createGraph(numCourses, edges) {
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;
}
function canFinish(numCourses, preq) {
const graph = createGraph(numCourses, preq);
let seen = new Set();
let seeing = new Set();
function explore(course) {
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;
}