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

前端 未结 4 971
傲寒
傲寒 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条回答
  •  迷失自我
    2021-02-15 18:31

    I just invented the following algorithm.

    • Start with an arbitrary vertex and mark it as 'visited'.
    • Go 'up' in the graph going to an arbitrary parent vertex and mark it as 'visited'.
    • Keep track of visited vertices on a stack.
    • If you reach a vertex with no parent vertices, check whether it is indeed the vertex from which all other vertices are reachable.
    • When reaching a vertex V already visited:
      1. Don't add the visited vertex V to the stack. Mark the previous vertex as the 'end' of a strongly connected component.
      2. Go down the stack until you reach the already visited vertex V. Along the way you remove all 'end' and 'start' markings. If the last marking removed was a 'start' marking, mark V as 'start', otherwise don't mark.
      3. Start at the top of the stack again and go down until you find a vertex with an unvisited parent (and continue with the first step of the algorithm) or until you reach the vertex marked as 'start' and check whether it is indeed a mother vertex from which all others are reachable.

    The idea is that, since any vertex should be reachable from the mother vertex, we can just take an arbitrary path upward, until we can't go higher.

    This way we only check the strongly connected components which can reach the starting vertex. In the case where there are a lot of strongly connected components with in-degree 0, this would be a clear advantage over Andy's algorithm.

提交回复
热议问题