这是一个拓扑排序的一个很好的例子。通过遍历遵循订单要求创建集合的最常见算法是Kahn's Algorithm。伪代码可以在下面看到,维基百科链接中的信息应该足以让你开始。
L ← Empty list that will contain the sorted elements
S ← Set of all nodes with no incoming edges
while S is non-empty do
remove a node n from S
add n to tail of L
for each node m with an edge e from n to m do
remove edge e from the graph
if m has no other incoming edges then
insert m into S
if graph has edges then
return error (graph has at least one cycle)
else
return L (a topologically sorted order)
请注意,“起始节点”将通过适当地表示图形中的传入边缘来执行。它将成为S
中唯一启动的节点。如果您想获得其他信息,请在评论中告诉我。
看起来应该这样做。让我来实现这个,然后我会分享我的反馈 –