Here are some ideas on this.
- There can only be multiple shortest paths from v->w through node x, either if there are multiple paths into x through the same vertice or if x is encountered multiple time at the same DFS level.
Proof: If there are multiple paths entering x
through the same vertex there are obviously multiple ways through x
. This is simple. Now let us assume there is only one way into x
through each vertex going into x
(at maximum).
If x has been encountered before, none of the current paths can contribute to another shortest path. Since x has been encountered before, all paths that can follow will be at least one longer than the previous shortest path. Hence none of these paths can contribute to the sum.
This means however we encounter each node at most once and are done. So a normal BFS is just fine.
- We do not even need to know the level, instead we can get the final number once we encounter the final node.
This can be compiled into a very simple algorithm, which is mainly just BFS.
- Mark nodes as visited as usual with BFS.
- Instead of adding just nodes to the queue in the DFS add nodes plus number of incoming paths.
- If a node that has been visited should be added ignore it.
- If you find a node again, which is currently in the queue, do not add it again, instead add the counts together.
- Propagate the counts on the queue when adding new nodes.
- when you encounter the final, the number that is stored with it, is the number of possible paths.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…