Python 3D Academyবাংলা

Topological order by DFS: finish last, go first

🌍 In real life. A build tool such as make has to compile a project whose files depend on each other. Ask it for the final program and it follows the chain: the program needs the library, the library needs the parser, the parser needs nothing. It finishes the parser first, then the library, then the program, each one only once everything it needs is finished.

That is the second classic way to find a topological order: depth-first search, the same DFS as Lesson 51.3, now following the arrows. A vertex is finished when DFS has gone through everything after it. The trick is to read the finishing order backwards.

The idea in one sentence: run DFS along the arrows, append each vertex to a list when it finishes (after all its arrows have been followed), and the reversed list is a topological order.

Its words:

  • enter: DFS arrives at a vertex and starts following its arrows
  • finish: every vertex its arrows lead to has been dealt with, so DFS backs out of it
  • finishing order (post-order): the order in which vertices finish; in a DAG, everything after a vertex finishes before it does
  • reachable from v: every vertex you can get to from v by following arrows; exactly the vertices that must come after v

How it works, step by step:

  1. go through the vertices in sorted order; start DFS at any not yet visited
  2. on entering a vertex, mark it visited and visit each arrow's target not yet visited
  3. when all its arrows are done, append the vertex to the finished list
  4. at the end, reverse the finished list

Watch the courses: DFS starts at A and runs down to F, which finishes first and so ends up last; each finished course slides into the front of the order:

Why reversing the finishing order works. Take any arrow v → w. When DFS looks at that arrow from v, w is in one of two states. Either w has not been visited, so DFS visits it right then and w finishes before v does. Or w is already finished. (The third possibility, w still being on the current path, would mean w leads back to v: a cycle, which a DAG doesn't have.) Either way w finishes before v, so in the reversed list v comes before w. That holds for every arrow, so the reversed list is a topological order. This is the build tool's rule, too: a file is finished only after everything it needs is finished.

What it costs, by counting. Each vertex is entered once and finishes once, and each arrow is looked at once from its start: O(V + E), the same as Kahn. For the six courses: 6 vertices and 6 arrows. The two methods often give different orders (here Kahn gave A, B, C, D, E, F and DFS gives B, D, A, C, E, F); both are valid.

Kahn or DFS? Kahn is easy to follow round by round and notices a cycle by itself (the count comes up short). DFS is short to write recursively and reuses the search you already know; on its own it does not notice cycles (Lesson 52.4 adds that).

def topo_dfs(graph):
    done, finished = set(), []

    def visit(v):
        done.add(v)
        for w in graph[v]:
            if w not in done:
                visit(w)
        finished.append(v)               # everything after v has finished first

    for v in sorted(graph):
        if v not in done:
            visit(v)
    return finished[::-1]                # last to finish goes first

print(topo_dfs({"A": ["C"], "B": ["C", "D"], "C": ["E"], "D": ["E"], "E": ["F"], "F": []}))
print(topo_dfs({"A": ["B"], "B": ["D"], "C": ["D"], "D": [], "E": ["F"], "F": []}))

def must_come_after(graph, v):
    seen, stack = {v}, [v]
    while stack:
        u = stack.pop()
        for w in graph[u]:
            if w not in seen:
                seen.add(w)
                stack.append(w)
    return sorted(seen - {v})            # everything reachable, except v itself

print(must_come_after({"A": ["C"], "B": ["C", "D"], "C": ["E"], "D": ["E"], "E": ["F"], "F": []}, "B"))   # all the courses B unlocks

Mistakes and edge cases.

  • appending on entry instead of on finish: the entry order (pre-order) is not a topological order; a vertex reached late through one arrow may need to come before one entered earlier
  • forgetting to reverse: the finishing order itself is a valid order of the arrows read backwards, so it looks plausible and is exactly wrong
  • starting from one vertex only: vertices not reachable from it are never visited; loop over every vertex and start DFS at any not yet done
  • deep chains: Python stops recursion at about 1,000 nested calls, so a chain of thousands of jobs needs an explicit stack instead, and that stack must also mark when each vertex finishes (a plain search stack, like must_come_after's, only finds what is reachable)
  • a cycle: this plain version quietly returns an order that breaks an arrow; check for cycles first (Lesson 52.4) or use Kahn

Quiz

  1. What does this print?

    def topo_dfs(graph):
        done, finished = set(), []
    
        def visit(v):
            done.add(v)
            for w in graph[v]:
                if w not in done:
                    visit(w)
            finished.append(v)               # everything after v has finished first
    
        for v in sorted(graph):
            if v not in done:
                visit(v)
        return finished[::-1]                # last to finish goes first
    
    print(topo_dfs({"A": ["B", "C"], "B": ["D"], "C": ["D"], "D": []}))
  2. For an arrow v → w in a DAG, which is always true during DFS?

    • w finishes before v
    • w is entered before v
    • w finishes after v
  3. Which courses must come after D?

    def must_come_after(graph, v):
        seen, stack = {v}, [v]
        while stack:
            u = stack.pop()
            for w in graph[u]:
                if w not in seen:
                    seen.add(w)
                    stack.append(w)
        return sorted(seen - {v})            # everything reachable, except v itself
    
    print(must_come_after({"A": ["C"], "B": ["C", "D"], "C": ["E"], "D": ["E"], "E": ["F"], "F": []}, "D"))
  4. This returns an order that puts D before C, although C → D. Which line is wrong?

    def topo_dfs(graph):
        done, order = set(), []
        def visit(v):
            done.add(v)
            order.append(v)
            for w in graph[v]:
                if w not in done:
                    visit(w)
        for v in sorted(graph):
            if v not in done:
                visit(v)
        return order

Coding tasks

  1. Write topo_dfs(graph): a topological order by DFS. Start DFS at the vertices in sorted order, follow each vertex's arrows in the order listed, record each vertex when it finishes, and return the reversed list. The graph is a DAG.

  2. Write must_come_after(graph, v): the sorted list of every vertex that must come after v, meaning every vertex reachable from v by following arrows (not v itself).