Skip to content

Commit e30b690

Browse files
committed
add: solve #261 Course Schedule with ts
1 parent 5cd4c26 commit e30b690

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
2+
/**
3+
* ์„ ์ˆ˜ ๊ณผ๋ชฉ๊ณผ ์ด์ˆ˜ ๊ณผ๋ชฉ ๊ด€๊ณ„๋ฅผ ํ™•์ธํ•˜์—ฌ ๋ชจ๋“  ๊ณผ๋ชฉ์„ ์ด์ˆ˜ํ•  ์ˆ˜ ์žˆ๋Š”์ง€ ์—ฌ๋ถ€ ํ™•์ธ.
4+
* @param {number} numCourses - ์ „์ฒด ๊ณผ๋ชฉ ์ˆ˜
5+
* @param {number[][]} prerequisites - ์„ ์ˆ˜ ๊ณผ๋ชฉ๊ณผ ์ด์ˆ˜ ๊ณผ๋ชฉ ๊ด€๊ณ„ ์ •๋ณด
6+
* @returns {boolean} - ๋ชจ๋“  ๊ณผ๋ชฉ์„ ์ˆ˜๊ฐ•ํ•  ์ˆ˜ ์žˆ๋Š”์ง€ ์—ฌ๋ถ€
7+
*
8+
* ์‹œ๊ฐ„ ๋ณต์žก๋„: O(V + E)
9+
* - ๊ทธ๋ž˜ํ”„๋ฅผ ์ƒ์„ฑํ•˜๋Š” ๊ณผ์ •์—์„œ O(E),
10+
* - bfs O(V + E),
11+
*
12+
* ๊ณต๊ฐ„ ๋ณต์žก๋„: O(V + E)
13+
* - ๊ฐ ๊ณผ๋ชฉ์— ๋Œ€ํ•œ ์„ ์ˆ˜ ๊ณผ๋ชฉ ์ €์žฅ์— O(V + E),
14+
* - prereqCount ์ €์žฅ์— O(V),
15+
* - ํ(queue) ์ €์žฅ์— O(V),
16+
*/
17+
function canFinish(numCourses: number, prerequisites: number[][]): boolean {
18+
// ๊ฐ ๊ณผ๋ชฉ์˜ ์„ ์ˆ˜ ๊ณผ๋ชฉ ์ •๋ณด๋ฅผ ์ €์žฅํ•˜๋Š” ๋ฆฌ์ŠคํŠธ
19+
const graph: number[][] = Array.from({ length: numCourses }, () => []);
20+
// ๊ฐ ๊ณผ๋ชฉ์˜ ์„ ์ˆ˜ ๊ณผ๋ชฉ ์ˆ˜ ๋ฅผ ์ €์žฅํ•˜๋Š” ๋ฐฐ์—ด
21+
const prereqCount: number[] = new Array(numCourses).fill(0);
22+
23+
// ๊ทธ๋ž˜ํ”„ ๋ฐ ์„ ์ˆ˜ ๊ณผ๋ชฉ ๊ฐœ์ˆ˜ ์ดˆ๊ธฐํ™”
24+
for (const [course, prereq] of prerequisites) {
25+
graph[prereq].push(course); // ์„ ์ˆ˜ ๊ณผ๋ชฉ์„ ๋“ค์–ด์•ผ ์ˆ˜๊ฐ• ๊ฐ€๋Šฅํ•œ ๊ณผ๋ชฉ ์ถ”๊ฐ€
26+
prereqCount[course]++; // ํ•ด๋‹น ๊ณผ๋ชฉ์˜ ์„ ์ˆ˜ ๊ณผ๋ชฉ ๊ฐœ์ˆ˜ ์ฆ๊ฐ€
27+
}
28+
29+
// ์„ ์ˆ˜ ๊ณผ๋ชฉ์ด ์—†๋Š” ๊ณผ๋ชฉ๋“ค์„ ์ €์žฅํ•  ํ
30+
const queue: number[] = [];
31+
32+
// ์„ ์ˆ˜ ๊ณผ๋ชฉ์ด ์—†๋Š” ๊ณผ๋ชฉ๋“ค์„ ํ์— ์ถ”๊ฐ€ (์ง„์ž… ์ฐจ์ˆ˜๊ฐ€ 0์ธ ๋…ธ๋“œ)
33+
for (let i = 0; i < numCourses; i++) {
34+
if (prereqCount[i] === 0) {
35+
queue.push(i);
36+
}
37+
}
38+
39+
// ์ˆ˜๊ฐ•ํ•œ ๊ณผ๋ชฉ ์ˆ˜
40+
let completedCourses = 0;
41+
42+
// ์„ ์ˆ˜ ๊ณผ๋ชฉ์ด ์—†๋Š” ๊ณผ๋ชฉ์„ ์‚ฌ์šฉํ•ด์„œ ๋‹ค์Œ ๊ณผ๋ชฉ์„ ์ˆ˜๊ฐ•
43+
while (queue.length > 0) {
44+
const current = queue.shift()!;
45+
completedCourses++; // ๊ณผ๋ชฉ ์ˆ˜๊ฐ• ์™„๋ฃŒ
46+
47+
// ํ˜„์žฌ ๊ณผ๋ชฉ์„ ์„ ์ˆ˜ ๊ณผ๋ชฉ์œผ๋กœ ํ•˜๋Š” ๋‹ค๋ฅธ ๊ณผ๋ชฉ๋“ค์˜ ์„ ์ˆ˜ ๊ณผ๋ชฉ ๊ฐœ์ˆ˜ ๊ฐ์†Œ
48+
for (const nextCourse of graph[current]) {
49+
prereqCount[nextCourse]--;
50+
51+
// ์„ ์ˆ˜ ๊ณผ๋ชฉ ๊ฐœ์ˆ˜๊ฐ€ 0์ด ๋˜๋ฉด ํ์— ์ถ”๊ฐ€ (๋” ์ด์ƒ ๊ธฐ๋‹ค๋ฆด ํ•„์š” ์—†์Œ)
52+
if (prereqCount[nextCourse] === 0) {
53+
queue.push(nextCourse);
54+
}
55+
}
56+
}
57+
58+
// ๋ชจ๋“  ๊ณผ๋ชฉ์„ ์ˆ˜๊ฐ• ์ˆ˜ ์žˆ๋Š”์ง€ ํ™•์ธ
59+
return completedCourses === numCourses;
60+
}
61+

0 commit comments

Comments
ย (0)