Data Structures · Graphs

Topological sort with DFS and a stack

Step through the C++ from the DAG-TopologicalSort demo. DFS starts from each unvisited node in alphabetical order. A node is pushed onto sorted_stack only after everything it points to has been pushed, so popping the stack gives an order where every arrow points forward.

The graph

Not visited On the DFS path (in recursion_stack) Finished, pushed (number = push order) Followed by DFS Led to a finished node Back edge: a cycle

What is happening

Call stack

    sorted_stack

      bottom

      Output (popped)

        visited
        recursion_stack
        Edit the graph

        dag_toposort.cpp

          The code is shortened from the activity version: parsing is left out, and the parameter lists are trimmed. The two sets and the stack are the same.