Topological Sort (DFS)
Topologically order a DAG using DFS finish times instead of in-degrees.
Open on GeeksforGeeks ↗Intuition
A vertex is only safe to record once everything it points to is finished. So append it on the way out of the recursion, not on the way in. That produces an order where every vertex appears after all its descendants — reverse it, and every edge points forward.
Approach
Record on exit, not entry
dfs(v): recurse into all unvisited neighbours first, then append v. This post-order guarantees each vertex is appended only after its whole reachable set.
Reverse the finish order
In the finish list a vertex sits after its descendants. Reversing puts it before them, which is exactly the topological requirement that edges point forward.
Kahn's vs DFS
Same result, different mechanics: Kahn's is iterative and detects cycles naturally; DFS is shorter but needs a separate grey/black check to spot cycles.
Solution & live demo
Edge cases
Outer loop starts DFS from every unvisited vertex; all components appear.
This plain version does not detect it — pair with the grey/black cycle check when input may be cyclic.
Finishes immediately; reversal is a no-op.