|
| 1 | +from typing import List |
| 2 | +from collections import defaultdict |
| 3 | + |
| 4 | +""" |
| 5 | +๋ฌธ์ : ์๊ฐ ํด์ผ ํ๋ ๋ชจ๋ ๊ฐ์ข์ ์ numCourses๊ฐ ์ฃผ์ด์ง ๋, ๋ชจ๋ ๊ฐ์ข๋ฅผ ๋๋ผ ์ ์์ผ๋ฉด true, ์๋๋ฉด false๋ฅผ ๋ฐํํด๋ผ. |
| 6 | + prerequisites[i] = [ai, bi], bi๋ฅผ ์๊ฐํ๊ธฐ ์ํด์ ๋ฐ๋์ ai๋ฅผ ์ฌ์ ์๊ฐํด์ผ๋ง ํ๋ค. |
| 7 | + |
| 8 | +ํ์ด: ์ฌ์ดํด์ด ์์ผ๋ฉด ์๊ฐ ๋ถ๊ฐ๋ฅ (์ํ ์ฐธ์กฐ), ์์ผ๋ฉด ์๊ฐ ๊ฐ๋ฅ |
| 9 | + ๊ฐ ๊ฐ์ข๋ฅผ Node๋ก ๋ณด๊ณ , ์ ํ ๊ณผ๋ชฉ ๊ด๊ณ๋ฅผ ๋ฐฉํฅ์ด ์๋ ๊ฐ์ (Edge)๋ก ๋ณด๋ฉด -> ๋ฐฉํฅ ๊ทธ๋ํ |
| 10 | + |
| 11 | + BFS ํ์ด |
| 12 | + 1. ๊ทธ๋ํ ๋ง๋ค๊ธฐ |
| 13 | + graph[a] = [b, c] ์ด๋ฉด a๋ฅผ ๋ฃ๊ธฐ ์ ์ b, c๋ฅผ ๋ค์ด์ผ ํ๋ค. |
| 14 | + graph[b] = [a] ์ด๋ฉด b๋ฅผ ๋ฃ๊ธฐ ์ ์ a๋ฅผ ๋ค์ด์ผ ํ๋ค. |
| 15 | +
|
| 16 | + 2. ์ง์
์ฐจ์ ๊ณ์ฐ |
| 17 | + ์ง์
์ฐจ์: ์ด๋ค ๋
ธ๋๋ก ๋ค์ด์ค๋ ๊ฐ์ ์ ์ |
| 18 | + ์ง์
์ฐจ์๊ฐ 0์ธ ๋
ธ๋๋ ๋ฐ๋ก ๋ค์ ์ ์๋ ๊ฐ์ |
| 19 | + |
| 20 | + 3. Queue์ ์ง์
์ฐจ์๊ฐ 0์ธ ๋
ธ๋๋ถํฐ ๋ฃ๊ณ ์์ |
| 21 | + Queue์์ ๊บผ๋ธ ๋
ธ๋๋ฅผ ๊ธฐ์ค์ผ๋ก, ์ฐ๊ฒฐ๋ ๋
ธ๋๋ค์ ์ง์
์ฐจ์๋ฅผ ํ๋์ฉ ์ค์ธ๋ค. |
| 22 | + ์ง์
์ฐจ์๊ฐ 0์ด ๋ ๋
ธ๋๋ ์๋ก Queue์ ์ถ๊ฐ |
| 23 | + |
| 24 | + 4, ์ฒ๋ฆฌ๋ ๋
ธ๋ ์๊ฐ ์ ์ฒด ๊ฐ์ ์์ ๊ฐ์ผ๋ฉด True, ์๋๋ฉด False |
| 25 | +
|
| 26 | +TC: O(V + E), V: ๊ณผ๋ชฉ ์, E: prerequisite ๊ด๊ณ ์ |
| 27 | +SC: O(V + E), ๊ทธ๋ํ + ์ง์
์ฐจ์ ๋ฐฐ์ด |
| 28 | +""" |
| 29 | + |
| 30 | +from collections import defaultdict, deque |
| 31 | + |
| 32 | +class Solution: |
| 33 | + def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: |
| 34 | + graph = defaultdict(list) |
| 35 | + indegree = [0] * numCourses |
| 36 | + |
| 37 | + # 1. ๊ทธ๋ํ ๋ง๋ค๊ธฐ, 2. ์ง์
์ฐจ์ ๊ณ์ฐ |
| 38 | + # ์๊ฐ ๊ฐ์, ์ฌ์ ๊ฐ์ |
| 39 | + for course, prereq in prerequisites: |
| 40 | + graph[prereq].append(course) |
| 41 | + indegree[course] += 1 |
| 42 | + |
| 43 | + # 3. Queue์ ์ง์
์ฐจ์๊ฐ 0์ธ ๋
ธ๋๋ถํฐ ๋ฃ๊ณ ์์ |
| 44 | + queue = deque([i for i in range(numCourses) if indegree[i] == 0]) |
| 45 | + completed = 0 |
| 46 | + |
| 47 | + # 4. BFS ํ์, ์ฒ๋ฆฌ๋ ๋
ธ๋ ์๊ฐ ์ ์ฒด ๊ฐ์ ์์ ๊ฐ์ผ๋ฉด True, ์๋๋ฉด False |
| 48 | + while queue: |
| 49 | + # queue์์ ๊บผ๋ธ ๊ณผ๋ชฉ์ ์๊ฐ ์๋ฃ ์ฒ๋ฆฌ |
| 50 | + current = queue.popleft() |
| 51 | + completed += 1 |
| 52 | + |
| 53 | + for neighbor in graph[current]: |
| 54 | + indegree[neighbor] -= 1 |
| 55 | + if indegree[neighbor] == 0: |
| 56 | + queue.append(neighbor) |
| 57 | + |
| 58 | + return completed == numCourses |
0 commit comments