[英]Algorithm to convert directed acyclic graphs to sequences
如果D依赖于B和C,而B和C都依赖于A,则我想要ABCD(或ACBD)作为结果; 即从图生成平面序列,以使所有节点都出现在其任何后代之前。 例如,在安装X之前,我们可能需要为X安装依赖项。
有什么好的算法?
在这样的问题中,术语对于找到正确的链接至关重要。
您描述的依赖项形成了部分排序的集合 (姿势)。 简而言之,这是一个带有订单运算符的集合,对于这些集合,某些对的比较可能不确定。 在您的示例中B
和C
是不可比的( B
都不依赖C
,或者C
都不依赖B
)。
订单运算符的扩展是一种尊重原始部分订单并为以前不可比拟的元素添加一些额外比较的扩展。 在极端情况下: 线性扩展会导致整体排序。 对于每个部分排序,都存在这种扩展 。
从位姿获得线性扩展的算法称为拓扑排序 。 Wikipedia提供以下非常简单的算法 :
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.