Last active
February 12, 2021 14:47
-
-
Save okaysidd/fcd96c5bee083d23dea55c6ac88784c1 to your computer and use it in GitHub Desktop.
This file contains 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
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