首页 > 编程语言 > 详细

拓扑排序

时间:2020-03-01 13:14:27      阅读:46      评论:0      收藏:0      [点我收藏+]

技术分享图片

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!