Skip to content

Commit 6104a75

Browse files
committed
course schedule solution
1 parent f06e0ee commit 6104a75

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
var canFinish = function (numCourses, prerequisites) {
2+
const graph = Array.from({ length: numCourses }, () => []);
3+
const inDegree = Array(numCourses).fill(0);
4+
5+
// ๊ทธ๋ž˜ํ”„ ๋งŒ๋“ค๊ธฐ ๋ฐ ์ง„์ž… ์ฐจ์ˆ˜ ๊ณ„์‚ฐ
6+
for (const [course, pre] of prerequisites) {
7+
graph[pre].push(course);
8+
inDegree[course]++;
9+
}
10+
11+
// ์ง„์ž… ์ฐจ์ˆ˜๊ฐ€ 0์ธ ๋…ธ๋“œ๋ถ€ํ„ฐ ์‹œ์ž‘
12+
const queue = [];
13+
for (let i = 0; i < numCourses; i++) {
14+
if (inDegree[i] === 0) queue.push(i);
15+
}
16+
17+
let count = 0;
18+
while (queue.length) {
19+
const node = queue.shift();
20+
count++;
21+
22+
for (const neighbor of graph[node]) {
23+
inDegree[neighbor]--;
24+
if (inDegree[neighbor] === 0) {
25+
queue.push(neighbor);
26+
}
27+
}
28+
}
29+
30+
return count === numCourses;
31+
};

0 commit comments

Comments
ย (0)