-
Notifications
You must be signed in to change notification settings - Fork 43
/
course-schedule-ii.py
286 lines (255 loc) · 9.04 KB
/
course-schedule-ii.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
"""
There are a total of numCourses courses you have to take, labeled from 0 to numCourses - 1. You are given an array prerequisites where prerequisites[i] = [ai, bi] indicates that you must take course bi first if you want to take course ai.
For example, the pair [0, 1], indicates that to take course 0 you have to first take course 1.
Return the ordering of courses you should take to finish all courses. If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array.
Example 1:
Input: numCourses = 2, prerequisites = [[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].
Example 2:
Input: numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]]
Output: [0,2,1,3]
Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0.
So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3].
Example 3:
Input: numCourses = 1, prerequisites = []
Output: [0]
Constraints:
1 <= numCourses <= 2000
0 <= prerequisites.length <= numCourses * (numCourses - 1)
prerequisites[i].length == 2
0 <= ai, bi < numCourses
ai != bi
All the pairs [ai, bi] are distinct.
"""
# V0
# IDEA : DFS + topological sort
# SAME dfs logic as LC 207 (Course Schedule)
from collections import defaultdict
class Solution(object):
def findOrder(self, numCourses, prerequisites):
# edge case
if not prerequisites:
return [x for x in range(numCourses)]
# help func : dfs
# 3 cases : 0 : unknown, 1 :visiting, 2 : visited
def dfs(idx, visited, g, res):
if visited[idx] == 1:
return False
# NOTE !!! if visited[idx] == 2, means already visited, return True directly (and check next idx in range(numCourses))
if visited[idx] == 2:
return True
visited[idx] = 1
"""
NOTE this !!!
1) for j in g[idx] (but not for i in range(numCourses))
2) go through idx in g[idx]
"""
for j in g[idx]:
if not dfs(j, visited, g, res):
return False
"""
don't forget to make idx as visited (visited[idx] = 2)
"""
visited[idx] = 2
"""
NOTE : the main difference between LC 207, 210
-> we append idx to res (our ans)
"""
res.append(idx)
return True
# init
visited = [0] * numCourses
# build grath
g = defaultdict(list)
for p in prerequisites:
g[p[0]].append(p[1])
res = []
"""
NOTE : go through idx in numCourses (for idx in range(numCourses))
"""
for idx in range(numCourses):
if not dfs(idx, visited, g, res):
return []
return res
# V0'
# IDEA : DFS + topological sort
# SAME dfs logic as LC 207 (Course Schedule)
import collections
class Solution:
def findOrder(self, numCourses, prerequisites):
# build graph
_graph = collections.defaultdict(list)
for i in range(len(prerequisites)):
_graph[prerequisites[i][0]].append(prerequisites[i][1])
visited = [0] * numCourses
res = []
for i in range(numCourses):
if not self.dfs(_graph, visited, i, res):
return []
print ("res = " + str(res))
return res
# 0 : unknown, 1 :visiting, 2 : visited
def dfs(self, _graph, visited, i, res):
if visited[i] == 1:
return False
if visited[i] == 2:
return True
visited[i] = 1
for item in _graph[i]:
if not self.dfs(_graph, visited, item, res):
return False
visited[i] = 2
res.append(i)
return True
# V0'
# IDEA : DFS + topological sort
# SAME dfs logic as LC 207 (Course Schedule)
class Solution(object):
def findOrder(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: List[int]
"""
graph = collections.defaultdict(list)
for u, v in prerequisites:
graph[u].append(v)
# 0 = Unknown, 1 = visiting, 2 = visited
visited = [0] * numCourses
path = []
for i in range(numCourses):
### NOTE : if not a valid "prerequisites", then will return NULL list
if not self.dfs(graph, visited, i, path):
return []
return path
def dfs(self, graph, visited, i, path):
# 0 = Unknown, 1 = visiting, 2 = visited
if visited[i] == 1: return False
if visited[i] == 2: return True
visited[i] = 1
for j in graph[i]:
if not self.dfs(graph, visited, j, path):
### NOTE : the quit condition
return False
visited[i] = 2
path.append(i)
return True
# V1
# IDEA : BFS
# http://bookshadow.com/weblog/2015/05/14/leetcode-course-schedule-ii/
class Solution:
# @param {integer} numCourses
# @param {integer[][]} prerequisites
# @return {integer[]}
def findOrder(self, numCourses, prerequisites):
degrees = [0] * numCourses
childs = [[] for x in range(numCourses)]
for pair in prerequisites:
degrees[pair[0]] += 1
childs[pair[1]].append(pair[0])
courses = set(range(numCourses))
flag = True
ans = []
while flag and len(courses):
flag = False
removeList = []
for x in courses:
if degrees[x] == 0:
for child in childs[x]:
degrees[child] -= 1
removeList.append(x)
flag = True
for x in removeList:
ans.append(x)
courses.remove(x)
return [[], ans][len(courses) == 0]
# V1'
# https://blog.csdn.net/fuxuemingzhu/article/details/83302328
# IDEA : DFS + topological sort
class Solution(object):
def findOrder(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: List[int]
"""
graph = collections.defaultdict(list)
for u, v in prerequisites:
graph[u].append(v)
# 0 = Unknown, 1 = visiting, 2 = visited
visited = [0] * numCourses
path = []
for i in range(numCourses):
if not self.dfs(graph, visited, i, path):
return []
return path
def dfs(self, graph, visited, i, path):
# 0 = Unknown, 1 = visiting, 2 = visited
if visited[i] == 1: return False
if visited[i] == 2: return True
visited[i] = 1
for j in graph[i]:
if not self.dfs(graph, visited, j, path):
return False
visited[i] = 2
path.append(i)
return True
# V1''
# https://blog.csdn.net/fuxuemingzhu/article/details/83302328
# IDEA : BFS
class Solution(object):
def findOrder(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: List[int]
"""
graph = collections.defaultdict(list)
indegrees = collections.defaultdict(int)
for u, v in prerequisites:
graph[v].append(u)
indegrees[u] += 1
path = []
for i in range(numCourses):
zeroDegree = False
for j in range(numCourses):
if indegrees[j] == 0:
zeroDegree = True
break
if not zeroDegree:
return []
indegrees[j] -= 1
path.append(j)
for node in graph[j]:
indegrees[node] -= 1
return path
# V2
from collections import defaultdict, deque
class Solution(object):
def findOrder(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: List[int]
"""
res, zero_in_degree_queue = [], deque()
in_degree, out_degree = defaultdict(set), defaultdict(set)
for i, j in prerequisites:
in_degree[i].add(j)
out_degree[j].add(i)
for i in xrange(numCourses):
if i not in in_degree:
zero_in_degree_queue.append(i)
while zero_in_degree_queue:
prerequisite = zero_in_degree_queue.popleft()
res.append(prerequisite)
if prerequisite in out_degree:
for course in out_degree[prerequisite]:
in_degree[course].discard(prerequisite)
if not in_degree[course]:
zero_in_degree_queue.append(course)
del out_degree[prerequisite]
if out_degree:
return []
return res