Graph DFS Topological Sort (Python)

Perform topological sort on a DAG using DFS with cycle detection via tri-color marking.

PythonData Integrity

Code

pythonsnippet
20 lines
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] == GRAY short-circuits the flow with an early raise when 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

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.