Skip to content

Instantly share code, notes, and snippets.

@okaysidd
Last active February 12, 2021 14:47
Show Gist options
  • Save okaysidd/fcd96c5bee083d23dea55c6ac88784c1 to your computer and use it in GitHub Desktop.
Save okaysidd/fcd96c5bee083d23dea55c6ac88784c1 to your computer and use it in GitHub Desktop.
def Topological_sort_with_cycle_check(adj):
visit = {x:0 for x in adj}
result = []
def dfs_visit(node):
if visit[node] == -1:
return False
if visit[node] == 1:
return True
visit[node] = -1
for neighbor in adj[node]:
if dfs_visit(neighbor) == False:
return False
visit[node] = 1
result.insert(0, node)
return True
for node in adj:
if dfs_visit(node) == False:
return 'Not a DAG'
return result
adj = {'A':['B','D'], 'B':['C','D'], 'C':[], 'D':['E'], 'E':[]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment