Skip to content

Topological sorting

一、207. 课程表 # 力扣官方题解

1、如果图 G 中存在环(即图 G 不是「有向无环图」),那么图 G 不存在拓扑排序。

这是因为假设图中存在环 x_1, x_2, \cdots, x_n, x_1 ,那么 x_1 在排列中必须出现在 x_n的前面,但 x_n 同时也必须出现在 x_1 的前面,因此不存在一个满足要求的排列,也就不存在拓扑排序;

2、如果图 G 是有向无环图,那么它的拓扑排序可能不止一种。举一个最极端的例子,如果图 G 值包含 n 个节点却没有任何边,那么任意一种编号的排列都可以作为拓扑排序。

二、在实现topological sorting的时候,一个非常重要的问题是circle,一旦有circle则无法进行topological sorting

三、使用 "入度" 和 "长度" :

1、一个node,如果它的 "入度" 为0,则表示它没有依赖其他节点

2、一个node,如果它的 "长度" 为0,则表示没有其它节点依赖它

算法思想

1、找到没有被依赖的

2、使用dependency relation构建的structure,如果能够进行topological sorting,则会形成hierarchy structure。

3、验证relation的分析不断地向下寻找,直到找到一个没有任何依赖的

4、应该是depth first search

5、这让我想起了topological sorting中,找到没有任何依赖的那个节点,然后反向不断地删减;其实,它和析构一个linked list是非常类似的,它们本质上都是对依赖关系的删除

wikipedia Topological sorting

In computer science, a topological sort or topological ordering of a directed graph is a linear ordering of its vertices such that for every directed edge uv from vertex u to vertex v, u comes before v in the ordering.

NOTE: 1、linear ordering是一个logical structure

For instance, the vertices of the graph may represent tasks to be performed, and the edges may represent constraints that one task must be performed before another; in this application, a topological ordering is just a valid sequence for the tasks.

NOTE: 1、上述是典型的dependency graph

A topological ordering is possible if and only if the graph has no directed cycles, that is, if it is a directed acyclic graph (DAG). Any DAG has at least one topological ordering, and algorithms are known for constructing a topological ordering of any DAG in linear time. Topological sorting has many applications especially in ranking problems such as feedback arc set.

Implementation

github Algo-Tree/Code/C++/Topological_sort.cpp

TODO

jianshu 拓扑排序(一)——有向图成环检测

csdn [ZZ]如何判断有向图是否成环

csdn 数据结构 图 有向无环图

csdn 拓扑排序判断有向图是否成环

leetcode

https://leetcode-cn.com/problems/course-schedule/solution/ke-cheng-biao-by-leetcode-solution/

https://leetcode-cn.com/problems/course-schedule-ii/solution/ke-cheng-biao-ii-by-leetcode-solution/

https://leetcode-cn.com/problems/course-schedule-iv/