Finding simple path between two vertices in a tree (undirected simple graph)

后端 未结 1 1703
情话喂你
情话喂你 2021-01-26 00:13

Given two vertices (A and B) and a tree (G) (undirected simple graph) - Find the vertices in the simple path between A and B in G. The algorithm should run in O(V) complexity.<

1条回答
  •  北海茫月
    2021-01-26 00:37

    If the problem is reconstructing the path after you found the distance, adjust the BFS in the following manner: start at one of the two vertices you want to connect, do a BFS. For every vertex v you discover, store its predecessor: if you discover vertex w via the edge u->w, then the predecessor of w is u. You can afterwards reconstruct the path in reverse order by starting at the target vertex and going from predecessor to predecessor until you reach the source vertex.

    Example:

         J
          \
           \
            A
           / \
          /   \
         B     C
        / \     \
       /   \     \
      D     E     F
                 / \
                /   \
               G     H
                \
                 \
                  I
    

    If you calculate the path from D to I, then you have the following predecessors:

    pre[I]=G
    pre[G]=F
    pre[F]=C
    pre[C]=A
    pre[A]=B        //A was discovered during the BFS via the edge B->A, so pre[A]=B
    pre[B]=D
    

    You'll also have some predecessors that don't lie on your path, so they won't matter during reconstruction. In the example, you'll also have

    pre[J]=A
    pre[E]=B
    pre[H]=F
    

    but for a path from the source of the BFS D to the target I you won't meet them during reconstruction.

    When you reconstruct the path starting at I, you get I<-G, then I<-G<-F, and so on until you have the full path in reverse order.

    If you only care about the path to one target, you can abort the BFS once you discovered the target; this won't change the complexity though. If however you want the paths to all targets from one source vertex, do the full BFS; if you do that, the predecessors will allow you to reconstruct the path to any target vertex.

    0 讨论(0)
提交回复
热议问题