First, we need to find out which nodes are part of any of the shortest path(s). We need to run a $BFS$ from the source node $S$ and save the distance of each node in array named $disS$. Now, run another $BFS$ from target node $T$ and save the distance of each node in array named $disT$.

Let the shortest path from node $S$ to node $T$ be $Y$. Now for each node $i$, if $disS_i$ + $disT_i$ == $Y$ then it is part of any of the shortest paths. Then, we need to use a $Multisource$ $Bfs$. Push all the nodes who are part of any of the shortest path(s) in the queue with distance 0. Run $Bfs$ and save the distance for each node.

Finally, you can answer the queries in $O(1)$.

Contributors

Statistics

87% Solution Ratio
MujahidEarliest, Feb '21
user.4477Fastest, 0.2s
user.4477Lightest, 32 MB
Jewel.SamaCShortest, 772B
Toph uses cookies. By continuing you agree to our Cookie Policy.