-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path210_findOrder.py
More file actions
38 lines (34 loc) · 1.32 KB
/
Copy path210_findOrder.py
File metadata and controls
38 lines (34 loc) · 1.32 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
class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
self.graph = [[] for _ in range(numCourses)]
self.graph = self.graph
for sub, pre in prerequisites:
self.graph[pre].append(sub)
self.visited = [False] * numCourses
self.onPath = [False] * numCourses
self.res = []
self.valid = True
for i in range(numCourses):
if not self.visited[i] and self.valid:
self.dfs(self.graph, i)
self.res.reverse()
print(self.valid)
return self.res if self.valid else []
def dfs(self, graph, i):
print(i)
if self.onPath[i] == True:
self.valid = False
return
self.visited[i] = True
self.onPath[i] = True
for neighbor in graph[i]:
if not self.visited[neighbor]:
self.dfs(graph, neighbor)
# if not self.valid:
# return
elif self.onPath[neighbor] == True: # 有一种情况需要考虑到:即,已经visited,这里边有可能有onpath的,这时应该判为valid = False
self.valid = False
return
self.onPath[i] = False
self.res.append(i)
# return