File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed
Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change 1+ """
2+ (해설을 보면서 따라 풀었습니다.)
3+
4+ Solution: graph 에서 circular 가 생기면 false, 아니면 true
5+
6+ n: numCourses
7+ p: number of preRequisites
8+ Time: O(n + p)
9+ Space: O(n + p)
10+ """
11+
12+
13+ class Solution :
14+ def canFinish (self , numCourses : int , prerequisites : List [List [int ]]) -> bool :
15+ graph = {i : [] for i in range (numCourses )}
16+ for crs , pre in prerequisites :
17+ graph [crs ].append (pre )
18+
19+ traversing = set ()
20+ finished = set ()
21+
22+ def dfs (crs ):
23+ if crs in traversing :
24+ return False
25+ if crs in finished :
26+ return True
27+
28+ traversing .add (crs )
29+ for pre in graph [crs ]:
30+ if not dfs (pre ):
31+ return False
32+ traversing .remove (crs )
33+ finished .add (crs )
34+ return True
35+
36+ for crs in graph :
37+ if not dfs (crs ):
38+ return False
39+ return True
You can’t perform that action at this time.
0 commit comments