-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path207_Course_Schedule.py
More file actions
34 lines (25 loc) · 922 Bytes
/
Copy path207_Course_Schedule.py
File metadata and controls
34 lines (25 loc) · 922 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
# building adjacency List
self.adjList = {}
for i in range(numCourses):
self.adjList[i] = []
for prerequisite in prerequisites:
self.adjList[prerequisite[0]].append(prerequisite[1])
# checking for cycle detection in every node
for i in range(numCourses):
if self.checkForCycle(i, set()):
return False
return True
# cycle detection
def checkForCycle(self, node: int, path: set[int]) -> bool:
if node in path:
return True
path.add(node)
for adjecent in self.adjList[node]:
if self.checkForCycle(adjecent, path):
path.remove(node)
return True
path.remove(node)
self.adjList[node] = []
return False