Search code examples
algorithmperformancelanguage-agnosticgraph

Most efficient way to visit nodes of a DAG in order


I have a large (100,000+ nodes) Directed Acyclic Graph (DAG) and would like to run a "visitor" type function on each node in order, where order is defined by the arrows in the graph. i.e. all parents of a node are guaranteed to be visited before the node itself.

If two nodes do not refer to each other directly or indirectly, then I don't care which order they are visited in.

What's the most efficient algorithm to do this?


Solution

  • You would have to perform a topological sort on the nodes, and visit the nodes in the resulting order.

    The complexity of such algorithm is O(|V| + |E|). This is arguably also a lower bound of what you want to do, since you a) want to visit all nodes, and b) can't really ignore any edges, since even a single edge can affect the ordering significantly.