views:

446

answers:

1

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 xth 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.

+4  A: 

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.

Matt J