File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
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
You canโt perform that action at this time.
0 commit comments