拓扑排序

拓扑排序解决的问题是有向图的节点排序。在有向无环图中,将图中的顶点以线性方式进行排序,使得对于任何的顶点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/

      

     

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kgduu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值