Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit c02bd14

Browse files
committed
207 course schedule
1 parent f72c149 commit c02bd14

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

javascript/207-canFinish.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
function createGraph(numCourses, edges) {
2+
const graph = Array.from({ length: numCourses }, () => []);
3+
4+
for (let edge of edges) {
5+
let [a, b] = edge;
6+
7+
if (!(a in graph)) graph[a] = [];
8+
if (!(b in graph)) graph[b] = [];
9+
10+
graph[a].push(b);
11+
}
12+
return graph;
13+
}
14+
15+
function canFinish(numCourses, preq) {
16+
const graph = createGraph(numCourses, preq);
17+
let seen = new Set();
18+
let seeing = new Set();
19+
20+
function explore(course) {
21+
if (seen.has(course)) return true;
22+
if (seeing.has(course)) return false;
23+
24+
seeing.add(course);
25+
for (let neighbor of graph[course]) {
26+
if (!explore(neighbor)) return false;
27+
}
28+
29+
seen.add(course);
30+
seeing.delete(course);
31+
return true;
32+
}
33+
34+
for (let i = 0; i < numCourses; i++) {
35+
if (!explore(i)) return false;
36+
}
37+
return true;
38+
};

0 commit comments

Comments
 (0)