您可以使用 BFS 的计数变化。
这个想法是保存一个映射dict:(v,depth)->#paths 的字典(条目是顶点和当前深度,值是从源到具有所需深度的该顶点的路径数)。
在 BFS 的每次迭代中,您都会跟踪路径的当前深度,并将找到的路径数添加到下一个级别。
如果您有 3 条通往 x 的路径和 4 条通往 y 的路径,都在深度 3 上,并且都有边缘 (x,u),(y,u) - 那么有 7 条通往 u 的路径 - 的想法3 通向x+(x,u),4 通向y+(y,u)。
应该是这样的:
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] 是图中A 中大小为n 的路径数表示从x 到y。我们找到第一个大于零的数字,并返回路径数。