##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
4 4 1 2 1 3 2 4 3 4
1 3 2 4
3 3 1 2 2 3 3 1
Input: Graph with cycle 1→2→3→1
DFS detects back edge (cycle).
Answer: -1
-1
6 6 1 2 1 3 2 4 3 4 4 5 4 6
Input: DAG with 6 vertices
DFS traversal produces valid ordering based on finish times.
Answer: 1 3 2 4 6 5
1 3 2 4 6 5
Given a directed acyclic graph (DAG) with vertices and edges, find a topological ordering of the vertices using DFS-based algorithm.
A topological ordering is a linear ordering of vertices such that for every directed edge , vertex comes before .
Output the topological ordering produced by starting DFS from the highest-numbered unvisited vertex and processing neighbors in reverse order of their vertex numbers. If the graph contains a cycle, output -1.
Each edge goes from to .
Any valid topological ordering, or if a cycle exists.
Input: DAG with edges 1→2, 1→3, 2→4, 3→4
DFS-based algorithm:
Answer: 1 3 2 4