Skip to content

Commit 29c744c

Browse files
committed
solve(w10): 207. Course Schedule
1 parent 761d218 commit 29c744c

File tree

1 file changed

+96
-0
lines changed

1 file changed

+96
-0
lines changed

course-schedule/seungriyou.py

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
# https://leetcode.com/problems/course-schedule/
2+
3+
from typing import List
4+
5+
class Solution:
6+
def canFinish_topo(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
7+
"""
8+
[Complexity]
9+
- TC: O(v + e) (v = numCourses, e = len(prerequisites))
10+
- SC: O(v + e) (graph)
11+
12+
[Approach]
13+
course schedule은 directed graph이므로, topological sort(BFS)를 이용해 방문한 노드의 개수가 numCourses와 같은지 확인한다.
14+
"""
15+
from collections import deque
16+
17+
# directed graph
18+
graph = [[] for _ in range(numCourses)]
19+
indegree = [0] * numCourses
20+
21+
for a, b in prerequisites:
22+
graph[b].append(a) # b -> a
23+
indegree[a] += 1
24+
25+
def topo_sort():
26+
# topological sort로 방문한 course 개수
27+
cnt = 0
28+
29+
# indegree가 0인 course 부터 시작
30+
q = deque([i for i in range(numCourses) if indegree[i] == 0])
31+
32+
while q:
33+
pos = q.popleft()
34+
35+
# 방문한 course 개수 세기
36+
cnt += 1
37+
38+
for npos in graph[pos]:
39+
# npos의 indegree 감소
40+
indegree[npos] -= 1
41+
# indegree[npos] == 0, 즉, npos를 방문하기 위한 prerequisite이 모두 방문되었다면, q에 npos 추가
42+
if indegree[npos] == 0:
43+
q.append(npos)
44+
45+
return cnt
46+
47+
return numCourses == topo_sort()
48+
49+
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
50+
"""
51+
[Complexity]
52+
- TC: O(v + e) (모든 노드 & 간선은 한 번 씩 방문, 재귀 호출도 첫 방문 시에만 수행)
53+
- SC: O(v + e) (graph)
54+
55+
[Approach]
56+
course schedule은 directed graph이므로, 모든 course를 끝낼 수 없다는 것은 directed graph에 cycle이 존재한다는 것이다.
57+
directed graph의 cycle 여부를 판단하기 위해 3-state DFS를 사용할 수 있다.
58+
1) 이전에 이미 방문한 상태 (visited)
59+
2) 현재 보고 있는 경로에 이미 존재하는 상태 (current_path) -> 재귀 실행 전에 추가 & 후에 제거
60+
3) 아직 방문하지 않은 상태
61+
"""
62+
63+
graph = [[] for _ in range(numCourses)] # directed graph
64+
visited = set() # 이전에 이미 방문한 노드 기록
65+
current_path = set() # 현재 경로에 이미 존재하는 노드를 만났다면, cycle이 존재하는 것
66+
67+
for a, b in prerequisites:
68+
graph[b].append(a) # b -> a
69+
70+
def is_cyclic(pos):
71+
# base condition
72+
# 1) pos가 current_path에 이미 존재한다면, cycle 발견
73+
if pos in current_path:
74+
return True
75+
# 2) pos가 이전에 이미 방문한 (+ cycle이 존재하지 않는 경로 위의) 노드라면, cycle 발견 X
76+
if pos in visited:
77+
return False
78+
79+
# recur (backtracking)
80+
current_path.add(pos) # 현재 경로에 추가
81+
for npos in graph[pos]:
82+
if is_cyclic(npos):
83+
return True
84+
current_path.remove(pos) # 현재 경로에서 제거
85+
86+
# 방문 처리 (+ cycle이 존재하지 않는 경로 위에 있음을 표시)
87+
visited.add(pos)
88+
89+
return False
90+
91+
for i in range(numCourses):
92+
# course schedule에 cycle이 존재한다면, 전체 course를 완료할 수 없음
93+
if is_cyclic(i):
94+
return False
95+
96+
return True

0 commit comments

Comments
 (0)