- Notifications
You must be signed in to change notification settings - Fork 625
/
Copy path210.py
53 lines (42 loc) · 1.7 KB
/
210.py
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
41
42
43
44
45
46
47
48
49
50
51
52
53
'''
There are a total of n courses you have to take, labeled from 0 to n-1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses.
There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.
Example 1:
Input: 2, [[1,0]]
Output: [0,1]
Explanation: There are a total of 2 courses to take. To take course 1 you should have finished
course 0. So the correct course order is [0,1] .
'''
classSolution(object):
deffindOrder(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: List[int]
"""
graph= [[] for_inrange(numCourses)]
visited= [Falsefor_inrange(numCourses)]
stack= [Falsefor_inrange(numCourses)]
forpairinprerequisites:
x, y=pair
graph[x].append(y)
result= []
forcourseinrange(numCourses):
ifvisited[course] ==False:
ifself.dfs(graph, visited, stack, course, result):
return []
returnresult
defdfs(self, graph, visited, stack, course, result):
visited[course] =True
stack[course] =True
forneighingraph[course]:
ifvisited[neigh] ==False:
ifself.dfs(graph, visited, stack, neigh, result):
returnTrue
elifstack[neigh]:
returnTrue
stack[course] =False
result.append(course)
returnFalse