Number of Ways to Arrive at Destination

You are in a city of `n` intersections numbered `0` to `n - 1`, joined by bi-directional roads. The input guarantees every intersection can be reached from any other and there is at most one road between any two intersections. You are given `n` and `roads`, where `roads[i] = [u_i, v_i, time_i]` means a road between `u_i` and `v_i` takes `time_i` minutes to travel. Return the number of ways to travel from intersection `0` to intersection `n - 1` in the shortest amount of time. Since the answer may be large, return it modulo `10^9 + 7`.

30:00

Number of Ways to Arrive at Destination
medium
Free written solution
Topics
Companies

You are in a city of n intersections numbered 0 to n - 1, joined by bi-directional roads. The input guarantees every intersection can be reached from any other and there is at most one road between any two intersections. You are given n and roads, where roads[i] = [u_i, v_i, time_i] means a road between u_i and v_i takes time_i minutes to travel. Return the number of ways to travel from intersection 0 to intersection n - 1 in the shortest amount of time. Since the answer may be large, return it modulo 10^9 + 7.

Example 1:
Input: {"n":7,"roads":[[0,6,7],[0,1,2],[1,2,3],[1,3,3],[6,3,3],[3,5,1],[6,5,1],[2,5,1],[0,4,5],[4,6,2]]}
Output: 4
Constraints:
  • 1≤n≤2001 \leq n \leq 200

  • n−1≤roads.length≤n(n−1)2n - 1 \leq \text{roads.length} \leq \frac{n (n - 1)}{2}

  • roads[i].length==3\text{roads}[i].\text{length} == 3

  • 0≤ui,vi≤n−10 \leq u_i, v_i \leq n - 1

  • 1≤timei≤1091 \leq \text{time}_i \leq 10^9

  • ui≠viu_i \neq v_i

  • There is at most one road connecting any two intersections

  • You can reach any intersection from any other intersection

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"n":7,"roads":[[0,6,7],[0,1,2],[1,2,3],[1,3,3],[6,3,3],[3,5,1],[6,5,1],[2,5,1],[0,4,5],[4,6,2]]}

Build the road map for 7 intersections and 10 roads. Start at 0 with time 0 and exactly 1 way to be there; every other time is unknown.

time ×ways at each intersection

723331115200 ×11∞ ×02∞ ×03∞ ×04∞ ×05∞ ×06∞ ×0

popped

-

neighbour

-

destination · node 6

t = ∞

ways = 0

min-heap (time, node) · 1

0, 0

settled

0/7

answer

...

blue: faster, reset ways

green: tie, add ways

Variables
VariableValue
n7
roads10
dist[0]0
ways[0]1
DepthFunction Call
Stack empty
0/28