title: Finding associated sources and destinations on a directed graph
body: <p><strong>Background</strong>:
  I have a collection of nodes which represents the intersection of product as it moves through a process.  These nodes are connected together into directed graphs.  There are several independent graphs, as product does not always intersect.</p>
  
  <p>Product will always start at an initial source node, one with no parents.  It will eventually end at a final destination node, one with no children.  A initial source may have one or more final destinations, and a final destination may have one or more initial sources.</p>
  
  <p>We are able to compile a list of desired initial sources to follow through a set of criteria given by a user.  These sources may, but not necessarily, belong to the same graph.</p>
  
  <p><strong>Objective</strong>:
  Given this list of initial sources, I need to be able to determine which initial sources correspond with which final destinations.  These sources and destinations must be grouped by graph, no duplicates.  In other words:</p>
  
  <ol>
  <li>Associate each node with its unique graph.</li>
  <li>Determine the initial sources that belong to each graph.</li>
  <li>Determine the final destinations that belong to each graph.</li>
  </ol>
  
  <p><strong>Example</strong>: if my list of initial sources is 1, 2, 3, 4, 5, 6, 7, and 8, I would have the following results (where my unknown destinations are A, C, D, E, G, K, L):</p>
  
  <pre><code>1,4,5,6 -&gt; A,G,K
  2 -&gt; C
  3 -&gt; D,E
  7,8 -&gt; L
  </code></pre>
  
  <p><strong>Question</strong>: What is an effective (and hopefully most efficient) algorithm for performing this task?</p>
  
  <p><strong>Current Solution</strong>, just for reference:</p>
  
  <pre><code>For each initial source:
      If we have not visited the initial source yet
          Mark as belonging to a new graph
  
          Add childrens to a list of nodes to visit.        
  
          For each node to visit:
              If we have not visited this node yet:
                  Mark as belonging to current graph
  
                  If there are no children
                      add to list of final destinations
                  End if
  
                  add all parents and all children to a list of nodes to visit
              End if
          Do next node
      End if
  Do next source
  </code></pre>
  
  <p>Obviously, there's a bit of extra overhead since we're going to be doing a lot of visitation of nodes we've already seen before, since we're visiting all children and all parents of every node.</p>