Skip to content

Commit 60843c3

Browse files
committed
feat(soobing): week10 > course-schedule
1 parent 3e3b658 commit 60843c3

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

β€Žcourse-schedule/soobing.tsβ€Ž

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* 문제 ν•΄μ„€
3+
* - κ·Έλž˜ν”„μ— 사이클이 μžˆλŠ”μ§€ μ—†λŠ”μ§€ ν™•μΈν•˜λŠ” 문제
4+
*
5+
* 아이디어
6+
* 1) κ·Έλž˜ν”„ 탐색 -> DFS, BFS
7+
* - κ·Έλž˜ν”„λ₯Ό νƒμƒ‰ν•˜λ©° 사이클이 μžˆλŠ”μ§€ μ—†λŠ”μ§€ ν™•μΈν•œλ‹€.
8+
* - ν˜„μž¬ κ²½λ‘œμ— 이미 λ°©λ¬Έν•œ λ…Έλ“œλ₯Ό λ‹€μ‹œ λ§Œλ‚˜λ©΄ 사이클 λ°œμƒ. = 1
9+
*/
10+
11+
function canFinish(numCourses: number, prerequisites: number[][]): boolean {
12+
const graph = new Map<number, number[]>();
13+
const visited: number[] = new Array(numCourses).fill(0); // 0: μ•ˆ λ‹€λ…€μ˜΄, 1: 사이클 확인 증(λ°©λ¬Έ 쀑), 2: 사이클 μ—†μŒ 확인 μ™„λ£Œ
14+
15+
// κ·Έλž˜ν”„ 생성
16+
for (const [course, preCourse] of prerequisites) {
17+
if (!graph.has(course)) graph.set(course, []);
18+
graph.get(course)!.push(preCourse);
19+
}
20+
21+
function hasCycle(index: number) {
22+
if (visited[index] === 1) return true;
23+
if (visited[index] === 2) return false;
24+
25+
visited[index] = 1;
26+
for (const preCourse of graph.get(index) || []) {
27+
if (hasCycle(preCourse)) return true;
28+
}
29+
visited[index] = 2;
30+
return false;
31+
}
32+
33+
for (let i = 0; i < numCourses; i++) {
34+
if (hasCycle(i)) return false;
35+
}
36+
return true;
37+
}

0 commit comments

Comments
Β (0)