Skip to content

Commit a69c944

Browse files
committed
feat: 207. Course Schedule
1 parent aca3c7d commit a69c944

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

โ€Žcourse-schedule/gwbaik9717.js

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
// n: numCourses, p: len(prerequisites)
2+
// Time complexity: O(n + p)
3+
// Space complexity: O(n + p)
4+
5+
class _Queue {
6+
constructor() {
7+
this.q = [];
8+
this.start = 0;
9+
this.end = 0;
10+
}
11+
12+
isEmpty() {
13+
return this.start === this.end;
14+
}
15+
16+
push(value) {
17+
this.q.push(value);
18+
this.end++;
19+
}
20+
21+
shift() {
22+
const rv = this.q[this.start];
23+
delete this.q[this.start++];
24+
25+
return rv;
26+
}
27+
}
28+
29+
/**
30+
* @param {number} numCourses
31+
* @param {number[][]} prerequisites
32+
* @return {boolean}
33+
*/
34+
var canFinish = function (numCourses, prerequisites) {
35+
const graph = Array.from({ length: numCourses }, () => []);
36+
const inDegree = Array.from({ length: numCourses }, () => 0);
37+
38+
for (const [end, start] of prerequisites) {
39+
graph[start].push(end);
40+
inDegree[end]++;
41+
}
42+
43+
const q = new _Queue();
44+
45+
for (let i = 0; i < numCourses; i++) {
46+
if (inDegree[i] === 0) {
47+
q.push(i);
48+
}
49+
}
50+
51+
let count = 0;
52+
53+
while (!q.isEmpty()) {
54+
const current = q.shift();
55+
count++;
56+
57+
// ํ˜„์žฌ ๋…ธ๋“œ์™€ ์—ฐ๊ฒฐ๋œ ๋‹ค๋ฅธ ๋…ธ๋“œ์˜ ์ฐจ์ˆ˜ ๊ฐ์†Œ
58+
for (const node of graph[current]) {
59+
inDegree[node] -= 1;
60+
61+
if (inDegree[node] === 0) {
62+
q.push(node);
63+
}
64+
}
65+
}
66+
67+
return count === numCourses;
68+
};

0 commit comments

Comments
ย (0)