-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path210. Course Schedule II.py
36 lines (36 loc) · 1.24 KB
/
210. Course Schedule 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
from collections import defaultdict
class Solution:
def findOrder(self, n: int, pre: List[List[int]]) -> List[int]:
g=defaultdict(list)
for i in range(len(pre)):
g[pre[i][0]].append(pre[i][1])
#print(g)
stack=[]
vis=[False]*n
dfsVis=[False]*n
for i in range(n):
if not vis[i]:
if self.checkCycle(i,g,vis,dfsVis,stack):
#print(vis,dfsVis)
return []
#print(vis,dfsVis)
return stack
def checkCycle(self,node,g,vis,dfsVis,stack):
vis[node]=True
dfsVis[node]=True
for i in g[node]:
if not vis[i]:
if self.checkCycle(i,g,vis,dfsVis,stack):
return True
elif dfsVis[i]:
return True
dfsVis[node]=False
stack.append(node)
return False
#def topSort(self,node,g,vis,stack):
# vis[node]=True
# for i in g[node]:
# if not vis[i]:
# self.topSort(i,g,vis,stack)
# stack.append(node)