d******4 发帖数: 132 | 1 欢迎各位大牛批评指导。统计背景,正在刷题,希望得到cs专家的指导。
class Solution:
# @param {integer} numCourses
# @param {integer[][]} prerequisites
# @return {integer[]}
def findOrder(self, numCourses, prerequisites):
if not prerequisites:
return range(numCourses)
dict={}
for e in prerequisites:
if e[0] not in dict:
dict[e[0]] = [e[1]]
else:
if e[1] not in dict[e[0]]:
dict[e[0]].append(e[1])
courseTaken=set()
res=[]
for e in dict:
stack=[e]
visited=set()
temp=[]
while stack:
curr=stack.pop()
if curr in visited:
return []
if curr in courseTaken:
continue
visited.add(curr)
courseTaken.add(curr)
temp.append(curr)
if curr in dict:
for pre in dict[curr]:
stack.append(pre)
res = res + temp[::-1]
for i in range(numCourses):
if i not in res:
res.append(i)
return res
|
|