Loading...
Given a directed acyclic graph (DAG) produce a linear ordering of vertices such that for every edge u→v, u appears before v. Non-uniqueness arises when independent subgraphs can be interleaved.
1KAHN_TOPO(G=(V,E)):2 inDeg[v] = 0 for v in V3 for each (u→v) in E: inDeg[v]++4 Q = queue of all v with inDeg[v]=05 order = []6 while Q not empty:7 u = pop(Q)8 append u to order9 for each (u→w) in Adj[u]:10 inDeg[w]--11 if inDeg[w] == 0: push w12 if |order| < |V|: return "cycle detected"13 return order
Each edge reduces some in-degree exactly once.