在有向非环路图DAG中寻找所有沿着特定顺序前进的边与点。
def top_sort(graph):
count = dict((gu, 0) for gu in graph)
for u in graph:
for v in graph[u]:
count[v] += 1
init = [u for u in graph if count[u] == 0]
res = []
while init:
u = init.pop()
res.append(u)
for v in graph[u]:
count[v] -= 1
if count[v] == 0:
init.append(v)
return res
(最近更新:2019年05月31日)
本文介绍了一种在有向无环图(DAG)中进行拓扑排序的算法实现。该算法通过计数每个节点的入度并使用队列来找到没有前驱的节点,从而确定节点间的依赖关系和正确的顺序。
822

被折叠的 条评论
为什么被折叠?



