如何在无向图中找到两个给定顶点之间的所有最短路径?

时间:2014-12-21 15:39:50

标签: algorithm graph

图G是无向图,其所有边是'重量是一样的。 u,v是2个给定顶点,如何在O(| V |)中找到图G中u和v之间的最短路径数?

| V |代表G中的顶点数。

1 个答案:

答案 0 :(得分:4)

您可以使用BFS的计数变化。

这个想法是保存一个映射dict:(v,depth)->#paths的字典(条目是顶点和当前深度,值是从源到此顶点的路径数,具有所需的深度)。

在BFS的每次迭代中,您都会跟踪路径的当前深度,并将找到的路径数添加到下一级。

如果您有3条通向x的路径和4条通往y的路径,深度为3,且两条都有边(x,u),(y,u) - 那么有7条路径可供选择到u - 导致x +(x,u)的3,导致y +(y,u)的4。

看起来应该是这样的:

findNumPaths(s,t):
   dict = {} //empty dictionary
   dict[(s,0)] = 1 //empty path
   queue <- new Queue()
   queue.add((s,0))
   lastDepth = -1
   while (!queue.isEmpty())
       (v,depth) = queue.pop()
       if depth > lastDepth && (t,lastDepth) is in dict: //found all shortest paths
            break
       for each edge (v,u):
           if (u,depth+1) is not entry in dict:
               dict[(u,depth+1)] = 0
               queue.push((u,depth+1)) //add u with depth+1 only once, no need for more!
           dict[(u,depth+1)] = dict[(u,depth+1)] + dict[v,depth]

       lastDepth = depth
   return dic[t]

如果使用字典哈希表,则运行时间为O(V + E)。


另一种解决方案(更容易编程但效率更低)是:

 1. Build the adjacency  matrix of the graph, let it be `A`. 
 2. Set `Curr = I` (identity matrix)
 3. while Curr[s][t] != 0:
    3.1. Calculate Curr = Curr * A //matrix multiplication
 4. Return Curr[s][t]

其有效的原因是(A^n)[x][y]是图n代表Ax的尺寸y的路径数。我们找到第一个高于零的数字,并返回路径数。

相关问题