拓扑排序

1.图

amap=dict()
amap[a]=[b,c,d]
amap[c]=[b,e]
amap[d]=[e]
amap[f]=[d,e]

2.每个节点的入度

            a b c d e f
          0 1 2 3 4 5 6
indegree=[0,0,2,1,2,3,0]

3.用于存放入度为0的节点的队列
q=queue.PriorityQueue()
4.用于存放拓扑排序的结果的列表
ans=[]


1.先将入度为0的节点都放入队列:

for j in range(1,n+1):
    if indegree[j]==0:
        q.put[j]

2.像上面的图那样,每处理完一个节点,将剩下的与它有关的节点的入度减1,若为0则放入队列:

while not q.empty():
    t=q.get()
    ans.append(t)    #从q中出队放入结果中
    if t in amap:
        for x in amap[t]:
            indegree[x]-=1    #入度减1
            if indegree[x]==0:    #为0的入队
                q.put(x)

参考:https://blog.csdn.net/qq_41713256/article/details/80805338

原文地址:https://www.cnblogs.com/holaworld/p/12388935.html