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

定义:

只有有向无环图(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.csdn.net/qinzhaokun/article/details/48541117

猜你喜欢

转载自blog.csdn.net/qq_41009682/article/details/81413170