Skip to content

Commit 2327fc1

Browse files
committed
solve 3
1 parent 2766ef7 commit 2327fc1

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

โ€Žcourse-schedule/pmjuu.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
'''
2+
์‹œ๊ฐ„ ๋ณต์žก๋„: O(V + E)
3+
- ์œ„์ƒ ์ •๋ ฌ(Topological Sort)์„ ์‚ฌ์šฉํ•˜์—ฌ ๋ชจ๋“  ๋…ธ๋“œ(๊ณผ๋ชฉ)์™€ ๊ฐ„์„ (์„ ์ˆ˜ ๊ณผ๋ชฉ ๊ด€๊ณ„)์„ ํƒ์ƒ‰ํ•˜๋ฏ€๋กœ O(V + E)์ž…๋‹ˆ๋‹ค.
4+
- V: ๋…ธ๋“œ(๊ณผ๋ชฉ) ๊ฐœ์ˆ˜ (numCourses)
5+
- E: ๊ฐ„์„ (์„ ์ˆ˜ ๊ณผ๋ชฉ ๊ด€๊ณ„) ๊ฐœ์ˆ˜ (prerequisites์˜ ๊ธธ์ด)
6+
7+
๊ณต๊ฐ„ ๋ณต์žก๋„: O(V + E)
8+
- ๊ทธ๋ž˜ํ”„๋ฅผ ์ธ์ ‘ ๋ฆฌ์ŠคํŠธ๋กœ ์ €์žฅํ•˜๋Š” ๋ฐ O(V + E) ๊ณต๊ฐ„์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค.
9+
- ์ถ”๊ฐ€์ ์œผ๋กœ ๋ฐฉ๋ฌธ ์ƒํƒœ๋ฅผ ์ €์žฅํ•˜๋Š” ๋ฆฌ์ŠคํŠธ๊ฐ€ ํ•„์š”ํ•˜์—ฌ O(V).
10+
- ๋”ฐ๋ผ์„œ ์ด ๊ณต๊ฐ„ ๋ณต์žก๋„๋Š” O(V + E)์ž…๋‹ˆ๋‹ค.
11+
'''
12+
13+
from collections import deque
14+
from typing import List
15+
16+
class Solution:
17+
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
18+
# ๊ทธ๋ž˜ํ”„ ์ดˆ๊ธฐํ™”
19+
graph = {i: [] for i in range(numCourses)}
20+
in_degree = {i: 0 for i in range(numCourses)}
21+
22+
# ์„ ์ˆ˜ ๊ณผ๋ชฉ ์ •๋ณด ๊ทธ๋ž˜ํ”„์— ์ €์žฅ
23+
for course, pre in prerequisites:
24+
graph[pre].append(course)
25+
in_degree[course] += 1
26+
27+
# ์ง„์ž… ์ฐจ์ˆ˜๊ฐ€ 0์ธ ๊ณผ๋ชฉ(์„ ์ˆ˜ ๊ณผ๋ชฉ์ด ์—†๋Š” ๊ณผ๋ชฉ)์„ ํ์— ์ถ”๊ฐ€
28+
queue = deque([course for course in in_degree if in_degree[course] == 0])
29+
completed_courses = 0
30+
31+
while queue:
32+
current = queue.popleft()
33+
completed_courses += 1
34+
35+
for neighbor in graph[current]:
36+
in_degree[neighbor] -= 1
37+
if in_degree[neighbor] == 0:
38+
queue.append(neighbor)
39+
40+
# ๋ชจ๋“  ๊ณผ๋ชฉ์„ ์ˆ˜๊ฐ•ํ•  ์ˆ˜ ์žˆ๋‹ค๋ฉด True, ์•„๋‹ˆ๋ฉด False
41+
return completed_courses == numCourses

0 commit comments

Comments
ย (0)