Find a vertex that all other vertices can be reached from in a digraph

前端 未结 4 973
傲寒
傲寒 2021-02-15 18:03

Given a directed graph, how can we determine whether or not there exists a vertex v, from which all other vertices are reachable. the algorithm should be as efficient as possibl

4条回答
  •  闹比i
    闹比i (楼主)
    2021-02-15 18:23

    Use Kosaraju's algorithm to find the strongly connected components of the graph in time O(|V|+|E|). If you then "shrink" each component to a single node, you'll be left with a directed acyclic graph. There exists a vertex from which all others can be reached if and only if there is exactly one vertex in the DAG with in-degree 0. This is the vertex you're looking for - the so-called "mother vertex".

    Note: This answer originally recommended using Tarjan's algorithm. Tarjan's is likely to be a bit faster, but it's also a bit more complex than Kosaraju's.

提交回复
热议问题