Created
December 25, 2019 03:19
-
-
Save alphaCoder/b1070f0b39ef95fce7d061db39661f9f to your computer and use it in GitHub Desktop.
Course Schedule II
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution: | |
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]: | |
marked = set() | |
order = [] | |
g = {} | |
cycle = False | |
onStack = [False for _ in range(numCourses)] | |
for v in range(numCourses): | |
g[v] = set() | |
for (u,v) in prerequisites: | |
g[u].add(v) | |
def dfs(v, visited): | |
nonlocal cycle | |
nonlocal onStack | |
visited.add(v) | |
onStack[v] = True | |
for u in g[v]: | |
if cycle: | |
return | |
elif u not in visited: | |
dfs(u, visited) | |
elif onStack[u]: | |
cycle = True | |
return | |
onStack[v] = False | |
order.append(v) | |
for k in list(g): | |
if k not in marked: | |
dfs(k, marked) | |
if cycle: | |
return [] | |
return order |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment