-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path210.课程表-ii.py
47 lines (38 loc) · 1.11 KB
/
210.课程表-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
#coding:utf-8
# @lc app=leetcode.cn id=210 lang=python
#
# [210] 课程表 II
#
# @lc code=start
class Solution(object):
def findOrder(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: List[int]
"""
node_out = dict((i, []) for i in range(numCourses))
node_in = dict((i, 0) for i in range(numCourses))
queue = list(idx for idx in range(numCourses))
for prerequisite in prerequisites:
i, o = prerequisite
node_out[o].append(i)
node_in[i] += 1
if i in queue:
queue.remove(i)
if not queue:
return []
result = []
while queue:
node = queue.pop(0)
result.append(node)
for n in node_out[node]:
node_in[n] -= 1
if not node_in[n]:
queue.append(n)
node_out[node] = []
if len(result) == numCourses:
return result
else:
return []
# @lc code=end