拓扑排序
2020-04-15 本文已影响0人
知识分享share
拓扑排序
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))