Graph serialization

后端 未结 4 1850
甜味超标
甜味超标 2020-12-13 05:55

I\'m looking for a simple algorithm to \'serialize\' a directed graph. In particular I\'ve got a set of files with interdependencies on their execution order, and I want to

4条回答
  •  抹茶落季
    2020-12-13 06:51

    Topological Sort (From Wikipedia):

    In graph theory, a topological sort or topological ordering of a directed acyclic graph (DAG) is a linear ordering of its nodes in which each node comes before all nodes to which it has outbound edges. Every DAG has one or more topological sorts.

    Pseudo code:

    L ← Empty list where we put the sorted elements
    Q ← Set of all nodes with no incoming edges
    while Q is non-empty do
        remove a node n from Q
        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 Q
    if graph has edges then
        output error message (graph has a cycle)
    else 
        output message (proposed topologically sorted order: L)
    

提交回复
热议问题