【发布时间】:2016-04-12 01:20:48
【问题描述】:
给定一个无向图 G = (V,E),是否有一种算法可以计算两个任意顶点 u 和 v 之间最短路径的总数?我认为我们可以利用 Dijkstra 算法。
【问题讨论】:
标签: algorithm graph shortest-path breadth-first-search depth-first-search
给定一个无向图 G = (V,E),是否有一种算法可以计算两个任意顶点 u 和 v 之间最短路径的总数?我认为我们可以利用 Dijkstra 算法。
【问题讨论】:
标签: algorithm graph shortest-path breadth-first-search depth-first-search
是的,您可以使用 dijkstra。创建一个数组,存储到任何节点的最短路径总数。称之为总。所有数组成员的初始值都是 0,除了 total[s] = 1 其中 s 是源。
在dijkstra循环中,比较一个节点的最小路径时,如果比较结果较小,则将该节点的总数组更新为当前节点的总数。如果相等,则将该节点的总数组与当前节点的总数相加。
伪代码取自维基百科,经过一些修改:
function Dijkstra(Graph, source):
create vertex set Q
for each vertex v in Graph: // Initialization
dist[v] ← INFINITY // Unknown distance from source to v
total[v] ← 0 // total number of shortest path
add v to Q // All nodes initially in Q (unvisited nodes)
dist[source] ← 0 // Distance from source to source
total[source] ← 1 // total number of shortest path of source is set to 1
while Q is not empty:
u ← vertex in Q with min dist[u] // Source node will be selected first
remove u from Q
for each neighbor v of u: // where v is still in Q.
alt ← dist[u] + length(u, v)
if alt < dist[v]: // A shorter path to v has been found
dist[v] ← alt
total[v] ← total[u] // update the total array of that node with the number of total array of current node
elseif alt = dist[v]
total[v] ← total[v] + total[u] // add the total array of that node with the number of total array of current node
return dist[], total[]
【讨论】: