Skip to content

Commit 708ba00

Browse files
authored
Merge pull request neetcode-gh#378 from anthonysim/asim/courseSchedule
207 course schedule js
2 parents f72c149 + c02bd14 commit 708ba00

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)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy