【发布时间】:2017-02-03 05:12:39
【问题描述】:
我正在寻找一种算法,它可以获取一个图并对其进行拓扑排序,从而生成一组列表,每个列表都包含不相交子图的拓扑排序顶点。
当一个节点依赖于两个不同列表中的一个节点时,困难的部分是合并列表。
这是我不完整的代码/伪代码,其中 graph 是一个字典 {node: [node, node, ...]}
将图形拓扑排序为不相交的列表
sorted_subgraphs = []
while graph:
cyclic = True
for node, edges in list(graph.items()):
for edge in edges:
if edge in graph:
break
else:
del graph[node]
cyclic = False
sub_sorted = []
for edge in edges:
bucket.extend(...) # Get the list with edge in it, and remove it from sorted_subgraphs
bucket.append(node)
sorted_subgraphs.append(bucket)
if cyclic:
raise Exception('Cyclic graph')
【问题讨论】: