LeetCode 210. [Python] Course Schedule II
原题链接
中等
作者:
徐辰潇
,
2020-03-29 05:57:11
,
所有人可见
,
阅读 719
class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
Dict = collections.defaultdict(list)
Indegree = collections.defaultdict(int)
for ele in prerequisites:
Dict[ele[1]].append(ele[0])
Indegree[ele[0]] += 1
res = []
Q = collections.deque([])
for i in range(numCourses):
if Indegree[i] == 0:
Q.append(i)
del Indegree[i]
if not Q:
return res
while Q:
parent = Q.popleft()
res.append(parent)
for child in Dict[parent]:
Indegree[child] -= 1
if Indegree[child] == 0:
Q.append(child)
del Indegree[child]
if len(Indegree) > 0:
return []
else:
return res