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

。_饼干妹妹 提交于 2020-01-11 03:29:07

问题


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(v2). I would also like it if level(v1) = level(v3) whenever (v1,v2) and (v3,v2) are in the graph. Also, the possible levels are discrete (might as well take them to be the natural numbers). The ideal case would be that level(v1) = level(v2) + 1 whenever (v1,v2) is in the graph and there is no other path from v1 to v2, but sometimes that isn't possible with the other constraints - e.g, consider a graph on five vertices with the edges (a,b) (b,d) (d,e) (a,c) (c,e).
Does anyone know a decent algorithm to solve this? My graphs are fairly small (|V| <= 25 or so), so I don't need something blazing fast - simplicity is more important.

My thinking so far is to just find a least element, assign it level 0, find all parents, assign them level 1, and resolve contradictions by adding +0.5 to the appropriate vertices, but this seems pretty awful.

Also, I get the feeling that it might be helpful to remove all "implicit" edges (i.e, remove (v1,v3) if the graph contains both (v1,v2) and (v2,v3).


回答1:


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}



回答2:


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



来源:https://stackoverflow.com/questions/3420685/how-to-assign-levels-to-vertices-of-an-acyclic-directed-graph

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!