Algorithm to find lowest common ancestor in directed acyclic graph?

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

    I am proposing O(|V| + |E|) time complexity solution, and i think this approach is correct otherwise please correct me.

    Given directed acyclic graph, we need to find LCA of two vertices v and w.

    Step1: Find shortest distance of all vertices from root vertex using bfs http://en.wikipedia.org/wiki/Breadth-first_search with time complexity O(|V| + |E|) and also find the parent of each vertices.

    Step2: Find the common ancestors of both the vertices by using parent until we reach root vertex Time complexity- 2|v|

    Step3: LCA will be that common ancestor which have maximum shortest distance.

    So, this is O(|V| + |E|) time complexity algorithm.

    Please, correct me if i am wrong or any other suggestions are welcome.

提交回复
热议问题