The algorithm can be described as follows:
Given a directed graph with n vertices and m edges. It is required to renumber its vertices in such a way that each edge leads from a vertex with a lower number to a vertex with a higher one.
In other words, it is required to find a permutation of vertices (topological order) corresponding to the order given by all the edges of the graph.
We will use depth-first search (dfs(v))
If we add our vertex to the beginning of a list at the time of exit from \(dfs(v)\) , then in the end in this list you get a topological sort.
Thus, the desired topological sort — this is sorted in descending order of exit times.