拓扑排序(定义,算法,例题)

拓扑排序仅适用于有向无环图(DAG),它是一种线性排序,确保对于所有有向边,起点总在终点之前。全序DAG的拓扑排序对应于其哈密顿路径。常见的拓扑排序算法包括Kahn算法和深度优先搜索(DFS)。本文将探讨这两种算法的原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

定义:

只有有向无环图(Directed Acyclic Graph,简称DAG )才有拓扑排序。
DAG必至少有一个入度为零的点和一个出度为零的点。

wikipedia中关于拓扑排序的定义:

In the field of 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.

就是说在拓扑排序中,对于任意一个有向边的起点和终点,在排序后起点总是在终点前。


在DAG中如果对于任意两点都可以找到一条路径使二者连通,则称该图是全序的,否则为偏序。
全序DAG的拓扑排序是该图的一条哈密顿路径,即经过该图的所有顶点。

算法:

常用的有Kahn算法和DFS算法。

Kahn
维基百科上的伪代码:

L ← Empty list that will contain the sorted elements
S ← Set of all nodes with no incoming edge
while S is non-empty do
    remove a node n from S
    add n to tail of 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 one cycle)
else 
    return L   (a topologically sorted order)

Depth-first search
维基百科上的伪代码:

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://blog.youkuaiyun.com/qinzhaokun/article/details/48541117

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值