|
| 1 | +/** |
| 2 | + * @link https://leetcode.com/problems/course-schedule/description/ |
| 3 | + * |
| 4 | + * 접근 방법 : |
| 5 | + * - 주어진 과목에서 선수 과목 사이클이 존재하는지 확인하기 위해서 dfs 사용 |
| 6 | + * - 사이클이 있다는 건 탐색 중에 다시 동일 과목이 등장한 경우니까, 과목별 결과 저장하기 위해서 visited 배열 사용 |
| 7 | + * |
| 8 | + * 시간복잡도 : O(n + e) |
| 9 | + * - n = 들어야 하는 과목 수 |
| 10 | + * - e = 선수 과목과 연결된 과목 수 |
| 11 | + * - 선수 과목 dfs 호출하고, 선수 과목과 연결된 과목도 호출함 |
| 12 | + * |
| 13 | + * 공간복잡도 : O(n + e) |
| 14 | + * - n = 들어야 하는 과목 수 |
| 15 | + * - e = 선수 과목과 연결된 과목 수 |
| 16 | + * - visited 배열 : O(n) |
| 17 | + * - Map : O(e) |
| 18 | + */ |
| 19 | + |
| 20 | +function canFinish(numCourses: number, prerequisites: number[][]): boolean { |
| 21 | + // 선수 과목을 키, 후속 과목을 값으로 저장 |
| 22 | + const map = new Map<number, number[]>(); |
| 23 | + |
| 24 | + for (const [course, prerequisite] of prerequisites) { |
| 25 | + if (!map.has(prerequisite)) map.set(prerequisite, []); |
| 26 | + map.get(prerequisite)!.push(course); |
| 27 | + } |
| 28 | + |
| 29 | + // 이미 탐색중인 과목인지 확인하기 위한 배열 |
| 30 | + // 미탐색 : 0, 탐색중: 1, 탐색완료 : 2로 처리 |
| 31 | + const visited = Array(numCourses).fill(0); |
| 32 | + |
| 33 | + const dfs = (course: number) => { |
| 34 | + // 탐색중이면 사이클이 발생 |
| 35 | + if (visited[course] === 1) return false; |
| 36 | + // 탐색 완료인 과목은 사이클이 없는 상태니까 true 리턴 |
| 37 | + if (visited[course] === 2) return true; |
| 38 | + |
| 39 | + // 탐색 시작 |
| 40 | + // 탐색 중인 상태로 변경 |
| 41 | + visited[course] = 1; |
| 42 | + |
| 43 | + const nextCourses = map.get(course) ?? []; |
| 44 | + |
| 45 | + // 후속 과목 모두 체크 |
| 46 | + for (const nextCourse of nextCourses) { |
| 47 | + if (!dfs(nextCourse)) return false; |
| 48 | + } |
| 49 | + |
| 50 | + // 탐색 완료 상태로 변경 |
| 51 | + visited[course] = 2; |
| 52 | + return true; |
| 53 | + }; |
| 54 | + |
| 55 | + // 들어야 하는 모든 과목에 대해 dfs 호출 |
| 56 | + for (let i = 0; i < numCourses; i++) { |
| 57 | + // 미탐색 노드만 탐색하도록 처리 |
| 58 | + if (visited[i] === 0 && !dfs(i)) return false; |
| 59 | + } |
| 60 | + |
| 61 | + return true; |
| 62 | +} |
0 commit comments