-
Notifications
You must be signed in to change notification settings - Fork 614
/
210.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] .
'''
class Solution(object):
def findOrder(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: List[int]
"""
graph = [[] for _ in range(numCourses)]
visited = [False for _ in range(numCourses)]
stack = [False for _ in range(numCourses)]
for pair in prerequisites:
x, y = pair
graph[x].append(y)
result = []
for course in range(numCourses):
if visited[course] == False:
if self.dfs(graph, visited, stack, course, result):
return []
return result
def dfs(self, graph, visited, stack, course, result):
visited[course] = True
stack[course] = True
for neigh in graph[course]:
if visited[neigh] == False:
if self.dfs(graph, visited, stack, neigh, result):
return True
elif stack[neigh]:
return True
stack[course] = False
result.append(course)
return False