Topological Sorting

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:

  1. Each vertex appears and only appears once.
  2. 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:

  1. Select a vertex with no predecessor (ie, in-degree 0) from the DAG graph and output it.
  2. Remove this vertex and all directed edges starting from it from the graph.
  3. 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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325817106&siteId=291194637
Recommended