美文网首页
拓扑排序

拓扑排序

作者: 知识分享share | 来源:发表于2020-04-15 18:04 被阅读0次

拓扑排序

graph = {
"a":["b","d"],
"b":["c"],
"d":["e","c"],
"e":["c"],
"c":[],
}
def TopologicalSort(graph):
degrees = dict((u,0) for u in graph) #{1:(a,0),2:(b,0)}
# print(degrees)
for u in graph:
# print(u)
for v in graph[u]:
# print(v)
degrees[v]+=1
queue = [u for u in graph if degrees[u]==0]
res=[]
while queue:
u = queue.pop()
res.append(u)
for v in graph[u]:
degrees[v]-=1
if degrees[v]==0:
queue.append(v)
return res
print(TopologicalSort(graph))

相关文章

网友评论

      本文标题:拓扑排序

      本文链接:https://www.haomeiwen.com/subject/jgkhvhtx.html