Skip to content

Commit b123b4d

Browse files
committed
couse-schedule solution (py)
1 parent e06e22c commit b123b4d

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

โ€Žcourse-schedule/hi-rachel.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
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

Comments
ย (0)