Number of Ways to Arrive at Destination

medium

There are n cities (0 .. n-1) connected by bidirectional roads roads[i] = [u, v, time]. Return the number of ways to travel from city 0 to city n-1 in the shortest possible time, modulo 10^9 + 7.

Hints

Run Dijkstra, but also keep a count of shortest paths to each city.
On a strictly shorter time to v, reset ways[v] = ways[u].
On an equal time (a tie), add: ways[v] += ways[u], modulo 1e9+7.

Common doubts

A shorter time invalidates all previously-counted routes to v; only u's shortest routes now reach v optimally.
Vertices settle in non-decreasing distance, so every shortest-path predecessor of v has already contributed before v is finalised.
The number of shortest paths can grow exponentially; the modulus keeps it in range.

Interview follow-ups

Same idea with BFS: reset on a smaller level, accumulate on an equal level.
Store a parent on the first (strictly-better) relaxation, then backtrack.

Fun facts

  • LeetCode 1976 — Dijkstra plus a one-line counting DP.
  • The same reset/accumulate rule generalizes to counting shortest paths in any weighted graph.

Asked at

AmazonGoogle
Frequently Sometimes Occasionally
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
There are 4 distinct routes from 0 to 6 all achieving the shortest time 7.
Example 2
Input: n = 4, roads = [[0,1,1],[0,2,1],[1,3,1],[2,3,1]]
Output: 2
0→1→3 and 0→2→3 both take time 2.
Constraints

- 1 <= n <= 200 - 0 <= roads.length <= n*(n-1)/2 - 1 <= time <= 10^9 - no duplicate roads, no self-loops

Solve this problem →