拓扑排序解决的问题是有向图的节点排序。在有向无环图中,将图中的顶点以线性方式进行排序,使得对于任何的顶点u到v的有向边(u,v),都可以u在v的前面。
1、Kahn算法
首先将所有入度为0的点组成一个集合S,每次从S里面取出一个顶点u放入L,然后遍历u的所有边(u,v1),(u,v2),...,并删除,并判断该边的另一个顶点,如果在移除这一条边后入度为0,则将这个顶点放入集合S中。不断的重复上面步骤。最后当集合为空时,检查图中是否还存在边。如果有,说明图一定有环。否则返回L,其为拓扑排序的结果。
L← Empty list that will contain the sorted elements
S ← Set of all nodes with no incoming edges
while S is non-empty do
remove a node n from S
insert n into L
for each node m with an edge e from n to m do
remove edge e from the graph
if m has no other incoming edges then
insert m into S
if graph has edges then
return error (graph has at least onecycle)
else
return L (a topologically sortedorder)
该方法的时间复杂度为O(V+E)
2、Depth-First search
将结点状态分为已经访问,未访问,正在访问状态。使用L来表示拓扑排序后的结果。遍历结点,如果结点为未访问状态,则以该结点作dfs,在dfs过程中,将当前的结点状态设置为正在访问,同时遍历当前结点的邻接结点
如果邻接结点为未访问状态,则在此邻接结点为起点,继续dfs,
如果邻接结点为已访问状态,说明图中存在环
在遍历完当前结点的所有邻接结点后,将当前结点状态设置为已经访问
L ← Empty list that will contain the sorted nodes
while there are unmarked nodes do
select an unmarked node n
visit(n)
function visit(node n)
if n has a permanent mark then return
if n has a temporary mark then stop (not a DAG)
mark n temporarily
for each node m with an edge from n to m do
visit(m)
mark n permanently
add n to head of L
参考资料:
https://en.wikipedia.org/w/index.php?title=Topological_sorting&oldid=854351542#Depth-first_search
https://oi-wiki.org/graph/topo/