How to assign “levels” to vertices of an acyclic directed graph?

后端 未结 2 1595
生来不讨喜
生来不讨喜 2020-12-17 05:31

I have an acyclic directed graph. I would like to assign levels to each vertex in a manner that guarantees that if the edge (v1,v2) is in the graph, then level(v1) > level(

相关标签:
2条回答
  • 2020-12-17 06:10

    You could use a topological sort to assign a unique number to each vertex with the property that you want Similarly you could go through the nodes in topological order and assign max(parents) + 1

    0 讨论(0)
  • 2020-12-17 06:14

    I think letting the level of v be the length of the longest directed path from v might work well for you. In Python:

    # the level of v is the length of the longest directed path from v
    def assignlevel(graph, v, level):
        if v not in level:
            if v not in graph or not graph[v]:
                level[v] = 0
            else:
                level[v] = max(assignlevel(graph, w, level) + 1 for w in graph[v])
        return level[v]
    
    g = {'a': ['b', 'c'], 'b': ['d'], 'd': ['e'], 'c': ['e']}
    l = {}
    for v in g:
        assignlevel(g, v, l)
    print l
    

    Output:

    {'a': 3, 'c': 1, 'b': 2, 'e': 0, 'd': 1}
    
    0 讨论(0)
提交回复
热议问题