Algorithm to find lowest common ancestor in directed acyclic graph?

后端 未结 10 932
孤独总比滥情好
孤独总比滥情好 2020-12-02 11:34

Imagine a directed acyclic graph as follows, where:

  • \"A\" is the root (there is always exactly one root)
  • each node knows its parent(s)
  • the no
10条回答
  •  被撕碎了的回忆
    2020-12-02 12:04

    Den Roman's link (Archived version) seems promising, but it seemed a little bit complicated to me, so I tried another approach. Here is a simple algorithm I used:

    Let say you want to compute LCA(x,y) with x and y two nodes. Each node must have a value color and count, resp. initialized to white and 0.

    1. Color all ancestors of x as blue (can be done using BFS)
    2. Color all blue ancestors of y as red (BFS again)
    3. For each red node in the graph, increment its parents' count by one

    Each red node having a count value set to 0 is a solution.

    There can be more than one solution, depending on your graph. For instance, consider this graph:

    LCA(4,5) possible solutions are 1 and 2.

    Note it still work if you want find the LCA of 3 nodes or more, you just need to add a different color for each of them.

提交回复
热议问题