i want to find an algorithm that when given a graph G=(V,E) and a node s from V, for any node v in V it finds the number of the shortest paths from s to v. i learned that BFS algorithm finds the shortest path from s to v, i just can't figure out how to use it in order to solve this problem. any help would be very appreciated.
Here is pseudo-code (meaning untested Python) for this.
path_count[s] = 1
length_to[s] = 0
todo = [s] # A queue
while len(todo):
v = todo.pop(0)
for w in edges(graph, v):
if w not in length_to:
length_to[w] = length_to[v] + 1
path_count[w] = 0
todo.append(w)
if length_to[w] == length_to[v] + 1:
path_count[w] += path_count[v]
After this length_to[v]
gives the length of the shortest path to v
and paths_to[v]
gives the number of shortest paths to v
. (Which is what you were looking for.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.