Graph serialization

后端 未结 4 1857
甜味超标
甜味超标 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:40

    I've come up with a fairly naive recursive algorithm (pseudocode):

    Map> source; // map of each object to its dependency list
    List dest; // destination list
    
    function resolve(a):
        if (dest.contains(a)) return;
        foreach (b in source[a]):
            resolve(b);
        dest.add(a);
    
    foreach (a in source):
        resolve(a);
    
    
    

    The biggest problem with this is that it has no ability to detect cyclic dependencies - it can go into infinite recursion (ie stack overflow ;-p). The only way around that that I can see would be to flip the recursive algorithm into an interative one with a manual stack, and manually check the stack for repeated elements.

    Anyone have something better?

    提交回复
    热议问题