-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path210_Course_Schedule_II.py
More file actions
40 lines (30 loc) · 1.05 KB
/
Copy path210_Course_Schedule_II.py
File metadata and controls
40 lines (30 loc) · 1.05 KB
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
35
36
37
38
39
40
class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
# building adjacency List
self.adjList = {}
self.res = []
self.visit = set()
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 []
return self.res
# 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] = []
if node not in self.visit:
self.res.append(node)
self.visit.add(node)
return False