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.
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.
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.
- 1 <= n <= 200 - 0 <= roads.length <= n*(n-1)/2 - 1 <= time <= 10^9 - no duplicate roads, no self-loops
This is Dijkstra with an extra bookkeeping array: alongside dist[v] (the shortest time to v), keep ways[v] (how many shortest-time routes reach v). Start with ways[0] = 1. When you relax an edge u → v with new time nd:
nd < dist[v] — a strictly better time: overwrite dist[v] and set ways[v] = ways[u] (all of u's shortest routes now extend to v).nd == dist[v] — a tie: ways[v] += ways[u] (mod 10^9+7) — more distinct shortest routes reach v.The answer is ways[n-1]. Everything else is standard Dijkstra (min-heap for O((V+E) log V), or a linear scan for O(V²)).
“Count all paths or shortest ones?”
Only the shortest-time paths.
“Why modulo?”
The count can be astronomically large.
I run Dijkstra but also carry a ways array: a strictly better time resets the count, a tie adds to it.
ways[n-1] modulo 1e9+7 is the answer.
Worked example — n = 7, a graph with two equally-short routes 0→…→6
if two shortest paths reach 6 with the same total time, ways[6] = 2
ways[v] = ways[u].
ways[v] += ways[u] (mod 1e9+7).
Predecessors settle first, so ways[v] is complete when v settles.
| Dijkstra scan + count | Dijkstra heap + count | |
|---|---|---|
| Find closest | linear scan | min-heap |
| Time | O(V²) | O((V+E) log V) |
| Counting | reset / accumulate | reset / accumulate |
Both count the same number of shortest paths. Full code is in the Approaches selector below.
Key takeaway
Run Dijkstra with a ways[] array: strictly-better time resets ways[v] = ways[u]; a tie does ways[v] += ways[u] (mod 1e9+7). Answer is ways[n-1].
relax u->v: nd < dist[v] -> reset ways[v]=ways[u]; nd == dist[v] -> ways[v]+=ways[u]