Topological Sort Problem
Calculate a sorting of vertices in DAG
Theory
If there’s an edge
Thus, taking vertices in descending order of finish time gives us a topological sort.
Implementation
def dfs(adj):
vis = set()
ret = []
for s in range(len(adj)):
if s not in vis:
dfs_visit(s, adj, vis, ret)
return ret.reverse()
def dfs_visit(s, adj, vis, ret):
vis.add(s)
for n in adj[s]:
if n not in vis:
dfs_visit(n, adj, vis)
ret.append(s)
Runtime
This is just a modified DFS, so it also takes