Algorithm to find lowest common ancestor in directed acyclic graph?

后端 未结 10 924
孤独总比滥情好
孤独总比滥情好 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:07

    Assume that you want to find the ancestors of x and y in a graph.

    Maintain an array of vectors- parents (storing parents of each node).

    1. Firstly do a bfs(keep storing parents of each vertex) and find all the ancestors of x (find parents of x and using parents, find all the ancestors of x) and store them in a vector. Also, store the depth of each parent in the vector.

    2. Find the ancestors of y using same method and store them in another vector. Now, you have two vectors storing the ancestors of x and y respectively along with their depth.

    3. LCA would be common ancestor with greatest depth. Depth is defined as longest distance from root(vertex with in_degree=0). Now, we can sort the vectors in decreasing order of their depths and find out the LCA. Using this method, we can even find multiple LCA's (if there).

提交回复
热议问题