File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution :
2+ def canFinish (self , numCourses : int , prerequisites : List [List [int ]]) -> bool :
3+
4+ # 재귀 DFS
5+ # 그래프 만들기
6+ # graph[i] = [j, ...] : i를 듣기 위해 선행해야 하는 과목j들 저장
7+ graph = [[] for _ in range (numCourses )]
8+ for i , j in prerequisites :
9+ graph [i ].append (j )
10+
11+ # visited
12+ # 0: 방문 안함
13+ # 1: 방문 중(현재 탐색 중)
14+ # 2: 방문 완료(사이클 없음 확인 완료)
15+ visited = [0 ]* numCourses
16+
17+ def dfs (course ):
18+ # 방문 중인데 또 방문 = 사이클 존재 -> False
19+ if visited [course ] == 1 :
20+ return False
21+
22+ # 이미 방문 완료(탐색 완료)
23+ if visited [course ] == 2 :
24+ return True
25+
26+ # 방문 중 표시
27+ visited [course ] = 1
28+
29+ # 선행과목들 DFS로 확인
30+ for i in graph [course ]:
31+ if not dfs (i ):
32+ return False
33+
34+ # 탐색 완료(방문 완료)
35+ visited [course ] = 2
36+
37+ return True
38+
39+ # 모든 과목 DFS 탐색
40+ for i in range (numCourses ):
41+ if not dfs (i ):
42+ return False
43+
44+ return True
You can’t perform that action at this time.
0 commit comments