How do I find all paths through a set of given nodes in a DAG?

Posted by Hanno Fietz on Stack Overflow See other posts from Stack Overflow or by Hanno Fietz
Published on 2008-11-26T13:39:15Z Indexed on 2010/04/19 17:33 UTC
Read the original article Hit count: 240

I have a list of items (blue nodes below) which are categorized by the users of my application. The categories themselves can be grouped and categorized themselves.

The resulting structure can be represented as a Directed Acyclic Graph (DAG) where the items are sinks at the bottom of the graph's topology and the top categories are sources. Note that while some of the categories might be well defined, a lot is going to be user defined and might be very messy.

Example:

example data

On that structure, I want to perform the following operations:

  • find all items (sinks) below a particular node (all items in Europe)
  • find all paths (if any) that pass through all of a set of n nodes (all items sent via SMTP from example.com)
  • find all nodes that lie below all of a set of nodes (intersection: goyish brown foods)

The first seems quite straightforward: start at the node, follow all possible paths to the bottom and collect the items there. However, is there a faster approach? Remembering the nodes I already passed through probably helps avoiding unnecessary repetition, but are there more optimizations?

How do I go about the second one? It seems that the first step would be to determine the height of each node in the set, as to determine at which one(s) to start and then find all paths below that which include the rest of the set. But is this the best (or even a good) approach?

The graph traversal algorithms listed at Wikipedia all seem to be concerned with either finding a particular node or the shortest or otherwise most effective route between two nodes. I think both is not what I want, or did I just fail to see how this applies to my problem? Where else should I read?

© Stack Overflow or respective owner

Related posts about algorithm

Related posts about directed-graph