import collections
class Solution:
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
courses = collections.defaultdict(set)
pres = collections.defaultdict(set)
for (x, y) in prerequisites:
courses[y].add(x) # 上完这个课之后可以上的
pres[x].add(y) # 这个课程的所有先修课程
no_pre = [i for i in range(numCourses) if not pres[i]]
res = []
count = 0
while no_pre:
take_course = no_pre.pop()
count += 1
res.append(take_course)
for i in courses[take_course]:
pres[i].remove(take_course)
if not pres[i]:
no_pre.append(i)
return res if count == numCourses else []