File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change
1
+ from collections import defaultdict
2
+
3
+
4
+ class Solution :
5
+ def canFinish (self , numCourses , prerequisites ):
6
+ graph = defaultdict (list )
7
+
8
+ for course , prerequisite in prerequisites :
9
+ graph [course ].append (prerequisite )
10
+
11
+ visit = ["unvisited" ] * numCourses
12
+
13
+ def detectCycle (course ):
14
+ if visit [course ] == "visiting" :
15
+ return True # Cycle detected
16
+ if visit [course ] == "visited" :
17
+ return False # Already fully visited
18
+
19
+ visit [course ] = "visiting" # Mark as visiting
20
+
21
+ for prerequisite in graph [course ]:
22
+ if detectCycle (prerequisite ):
23
+ return True
24
+
25
+ visit [course ] = "visited" # Mark as fully visited
26
+
27
+ return False
28
+
29
+ # Perform cycle detection for all courses
30
+ for course in range (numCourses ):
31
+ if detectCycle (course ):
32
+ return False
33
+
34
+ return True
You can’t perform that action at this time.
0 commit comments