逆向的拓扑排序(python)

拓扑排序概念请点击处查看,逆拓扑即考虑出度为0的情况。python代码如下(采用字典构建图的邻接结构实现):

def inverseTopsortTask(G):
    topRes = [] # 存储拓扑排序后的结果
    vexDegree = {} # 存储各节点的出度
    # 获取图的所有节点
    vertex = [vex for vex in G.keys()]
    for vexSet in G.values():
        for vex in vexSet:
            if vex not in vertex:
                vertex.append(vex)
    # 计算每个结点的出度
    for vex in vertex:
        if vex in G.keys():
            vexDegree[vex] = len(G[vex])
        else:
            vexDegree[vex] = 0
    #先将出度为0的结点入栈
    stack = [vex for vex in vexDegree.keys() if vexDegree[vex] == 0]
    #进行拓扑排序
    while len(stack) != 0:
        node = stack.pop(-1)
        topRes.append(node)
        #将其它节点指向node的结点的边删去,即删去边(vex(其它结点), node),即含有的node结点的出度减一
        for vex in G.keys():
            if node in G[vex]:
                vexDegree[vex] -= 1
                if vexDegree[vex] == 0:
                    stack.append(vex)
    if len(topRes) == len(vertex):
        print(topRes)
        return topRes
    else:
        print("有环")
G = {5:[3,4], 4:[8,10], 8:[11]}
inverseTopsort(G)

输出结果如下:

[11, 8, 10, 4, 3, 5]

你可能感兴趣的:(算法,编程语言,逆向拓扑排序,python)