$\huge{\color{Cadetblue}\text{Topological sort}}$
Given a , find a topological sort of its vertices. A topological sort of a directed graph is a linear ordering of its vertices such that for every directed edge from vertex to vertex , comes before in the ordering. We can think of the sort as a permutation of the vertices of the graph such that each vertex appears before all of its descendants. Another way is to visualize it as a flattened graph, where the edges are removed and the vertices are ordered in such a way that the dependencies (predecessor relationships) between the vertices are preserved. Note that a topological sort is not necessarily unique.
A topological sort can be achieved by running a DFS on the graph. While the graph is traversed, we prepend each node to a linked list when it is assigned a finish time (colored black). The resulting list is then the topological sort of the graph. The time complexity of the algorithm is , since we need to run a DFS on the graph and list insertion takes time.
The program omits the color attribute of the nodes, since it is not needed to find a topological sort. Note that the program outputs a possible topological sort of the graph which is not necessarily unique.
Implementation: TPS
We have the following DAG representing a dependency graph of tasks to be performed, where an arrow from task to task means that task must be completed before task :
The topological sort of the above graph is a linear ordering of its vertices such that for every directed edge from vertex to vertex , comes before in the ordering. A topological sort of the above graph is the permutation :
Note that this topological sort is . For example, the permutation is another valid topological sort of the same graph.
