Graph DFS Topological Sort (Python)
Perform topological sort on a DAG using DFS with cycle detection via tri-color marking.
Code
def topological_sort(graph):
WHITE, GRAY, BLACK = 0, 1, 2
color = {n: WHITE for n in graph}
result = []
def dfs(node):
if color[node] == GRAY:
raise ValueError(f"cycle at {node}")
if color[node] == BLACK:
return
color[node] = GRAY
for neighbor in graph.get(node, []):
dfs(neighbor)
color[node] = BLACK
result.append(node)
for n in graph:
if color[n] == WHITE:
dfs(n)
return result[::-1]How the snippet works
One way to read it: the functions topological_sort and dfs, doing all the work.
Iteration happens inside for neighbor in graph.get(node, []) — everything outside it runs once. Invalid states are rejected up front: it throws ValueError instead of continuing with bad data.
What to watch for
- The guard
color[node] == GRAYshort-circuits the flow with an earlyraisewhen its condition holds.
Applying it
Entry signature: def topological_sort(graph)
topological_sort is what another module would consume; nothing else here is load-bearing for callers.
Statements that matter
def dfs(node):
if color[node] == GRAY:
raise ValueError(f"cycle at {node}")
if color[node] == BLACK:
return
color[node] = GRAY
for neighbor in graph.get(node, []):
dfs(neighbor)
color[node] = BLACK
result.append(node)
Interactive Tools for This Topic
Line SorterSort text lines ascending or descending with numeric-aware ordering, duplicate removal, empty-line filtering, and locale-aware comparison.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Does the code validate its input?
- The code refuses to continue: `ValueError` is thrown while the state is still recoverable.
- Will the snippet run without installing packages?
- Yes, it runs as-is — nothing outside the built-in APIs is referenced. The file defines `topological_sort`, `dfs` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.