简体   繁体   中英

O(E+V) algorithm to compute number of shortest paths between 2 nodes on given graph

When Given a graph G with vertices and edges |V| and |E| respectively and vertices u and t, write a O(|E|+|V|) algorithm to compute the number of shortest paths from u to t, ie if there are 5 paths of length 4 with length 4 being the shortest path from u to t then the algorithm will output 5.

I know that the algorithm must somehow incorporate either a DFS or a BFS due to its run-time as each have a O(|E|+|V|) run-time, but I am a bit stuck. I tried implementing something where it would do a DFS repeatedly with the algorithm terminating at t but it this became problematic for deciding which nodes to set as visited and which to reset after each iteraition.

Thanks in advance!

You can use breadth-first search. For each vertex, keep track of:

  • the shortest path length from u to that vertex
    • Whenever you process a given vertex, you set this property for all of its neighbors that don't already have this property set.
    • This doubles as a "has already been enqueued" flag: you initially set to a sentinel value such as ɴɪʟ or ∞, and only update it once for any given vertex. So you don't need a separate flag to track visited vertices.
  • the number of shortest paths from u to that vertex
    • Whenever you process a given vertex, you increase this property appropriately for all of its neighbors whose shortest path length from u is greater than that of the vertex you're processing.
    • Note that you'll update this property many times for some vertices, but that's OK, because you only update it once per edge.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM