1. What is topological sort
In graph theory, Topological Sorting is a linear sequence of all vertices of a Directed Acyclic Graph (DAG) . And the sequence must satisfy the following two conditions:
- Each vertex appears and only appears once.
- If there is a path from vertex A to vertex B, then vertex A appears before vertex B in the sequence.
Directed acyclic graphs (DAGs) have topological sorting, and non-DAG graphs do not have topological sorting.
For example, the following image:
It is a DAG graph, so how to write its topological sort? Here is a more common method:
- Select a vertex with no predecessor (ie, in-degree 0) from the DAG graph and output it.
- Remove this vertex and all directed edges starting from it from the graph.
- Repeat 1 and 2 until the current DAG graph is empty or there are no vertices without predecessors in the current graph . The latter case shows that there must be cycles in a directed graph.
Therefore, the topologically sorted result is { 1, 2, 4, 3, 5 }.
In general, a directed acyclic graph can have one or more topologically sorted sequences.
https://blog.csdn.net/lisonglisonglisong/article/details/45543451