简体   繁体   English

酰基有向图的BFS遍历算法

[英]Algorithm for BFS traveral of an acylic directed graph

I'm looking for an elegant Python program that does a BFS traveral of a DAG: 我正在寻找一个执行DAG的BFS遍历的优雅Python程序:

Node A is connected to B ( A->B ) if A "depends on" B (think of python package Foo "depending upon" Bar: Foo->Bar). 如果A“依赖” B(将python包Foo“依赖” Bar认为:Foo-> Bar),则将节点A连接到B( A->B )。

In a graph of about 7000 such nodes, I want to sort all nodes such that for all possible (i, j) where 1>=i<j<=7000 .. depends(Ni, Nj) is False. 在大约7000个这样的节点的图中,我想对所有节点进行排序,使得对于所有可能的(i, j) ,其中1>=i<j<=7000 depends(Ni, Nj)为False。 depends(A, B) = True if and only if A->B or A "depends on" B .. and Nx is the node occuring in x th position in the sorted list. 当且仅当A->B或A“依赖于” B ..并且Nx是出现在排序列表中第x个位置的节点时,depends(A,B)= True。

Note: A node can have multiple parents. 注意:一个节点可以有多个父节点。 Eg: A->C and B->C. 例如:A-> C和B-> C。 Therefore, according to the above sorting rule, A and B must come before C. 因此,根据上述排序规则,A和B必须排在C之前。

If I am reading the question correctly, it looks like you want a topological sort . 如果我正确地阅读了该问题,则看起来您想要一种拓扑排序 The most efficient algorithm (O(V+E)) for doing this was proposed by Tarjan , and a Python implementation can be found here . Tarjan提出了用于执行此操作的最有效算法(O(V + E)),可以在此处找到Python实现。

Off-topic, but it seems as though your package dependency analogy is reversed; 偏离主题,但好像您的程序包依赖类推倒了; I would think that "A depends on B" would imply "B->A", but of course this will not change the structure of the tree, merely reverse it. 我认为“ A取决于B”将意味着“ B-> A”,但是当然这不会改变树的结构,而只是反转它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM