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

烈酒焚心 提交于 2019-12-04 06:43:44

问题


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.

for instance - find the vertices in the simple path between a and b:

d<->k
k<->a
k<->b

the answer should be : k

I have tried to modify BFS to accomplish the goal but it doesn't seem to work so far.

Any suggestions?


回答1:


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.



来源:https://stackoverflow.com/questions/15708422/finding-simple-path-between-two-vertices-in-a-tree-undirected-simple-graph

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!