topological sort, depth first search
class Solution(object):
def findOrder(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: List[int]
"""
res=[]
graph=[[] for _ in range(numCourses)]
visit=[0]*numCourses
for x,y in prerequisites:
graph[y].append(x)
def dfs_visit(n):
if visit[n]==-1:return False
if visit[n]==1: return True
if visit[n]==0:
visit[n]=-1
for m in graph[n]:
if not dfs_visit(m):
return False
visit[n]=1
res.insert(0,n)
return True
for i in range(numCourses):
if visit[i]==0:
if not dfs_visit(i):
return []
return res
Kahn's algorithm , breadth first search
class Solution(object):
def findOrder(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: List[int]
"""
res=[]
graph_in,graph_out=collections.defaultdict(set), collections.defaultdict(set)
for x,y in prerequisites:
graph_in[x].add(y)
graph_out[y].add(x)
s=set([i for i in range(numCourses) if i not in graph_in])
while s:
n=s.pop()
res.append(n)
for m in graph_out[n]:
graph_in[m].discard(n)
if not graph_in[m]:
del graph_in[m]
s.add(m)
if graph_in:
return []
return res