I'm looking for an elegant Python program that does a BFS traveral of a DAG:
Node A is connected to B ( A->B
) if A "depends on" B (think of python package Foo "depending upon" Bar: Foo->Bar).
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. 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.
Note: A node can have multiple parents. Eg: A->C and B->C. Therefore, according to the above sorting rule, A and B must come before 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 .
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.