Number of Ways to Arrive at Destination (LeetCode 1976): Solution and Explanation
In a city of weighted two-way roads, count how many different routes from intersection 0 to intersection n - 1 take the minimum possible time, modulo 10^9 + 7.
Intuition
Finding the minimum time alone is a textbook Dijkstra problem. The question is how to count the routes that achieve it without listing them, since there can be exponentially many.
Think about the last road of any shortest route to v. It comes from some neighbour u with dist[u] + t = dist[v], and the part before it must itself be a shortest route to u. So the number of shortest ways to v is the sum of ways[u] over every such neighbour u.
Dijkstra pops nodes in increasing time order. When u is popped, every node that could lie before it on a shortest route has already been popped, so ways[u] is complete and safe to pass forward.
That gives two rules while relaxing a road. If it gives v a strictly shorter time, every count gathered so far for v belonged to slower routes, so throw them away: ways[v] = ways[u]. If it ties the current best, it adds a new family of routes: ways[v] += ways[u].
Times reach about 200 roads times 10^9 minutes, roughly 2 * 10^11, which overflows a 32-bit integer. Distances must be 64-bit, while the counts stay small because they are reduced modulo 10^9 + 7.
Approach: Dijkstra with path counting
- Build an adjacency list from the two-way roads.
- Set
dist[0] = 0,ways[0] = 1, every other distance to infinity, and push(0, 0)onto a min-heap. - Pop
(d, u). Ifd > dist[u], the entry is stale; skip it. - For each road
(u, v, t), computend = d + tin 64-bit arithmetic. - If
nd < dist[v], setdist[v] = nd,ways[v] = ways[u], and push(nd, v). - Else if
nd == dist[v], setways[v] = (ways[v] + ways[u]) % (10^9 + 7). - When the heap is empty, return
ways[n - 1].
Step-by-step example
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]]
- Pop 0 at time 0. Roads give node 6 time 7, node 1 time 2 and node 4 time 5, each with 1 way.
- Pop 1 at time 2. Nodes 2 and 3 get time 5 with 1 way each.
- Pop 2 at time 5. Node 5 gets time 6 with 1 way.
- Pop 3 at time 5. 5 + 1 = 6 ties node 5, so ways[5] = 2. The road to 6 would take 8, which is slower, so it is ignored.
- Pop 4 at time 5. 5 + 2 = 7 ties node 6, so ways[6] = 1 + 1 = 2.
- Pop 5 at time 6. 6 + 1 = 7 ties node 6 again, so ways[6] = 2 + 2 = 4. Popping 6 at time 7 makes it final: return 4.
Code: Python, Java, C++
1class Solution:
2 def countPaths(self, n: int, roads: List[List[int]]) -> int:
3 MOD = 10**9 + 7
4 graph = [[] for _ in range(n)]
5 for u, v, t in roads:
6 graph[u].append((v, t))
7 graph[v].append((u, t))
8 dist = [float('inf')] * n
9 ways = [0] * n
10 dist[0] = 0
11 ways[0] = 1
12 heap = [(0, 0)]
13 while heap:
14 d, u = heapq.heappop(heap)
15 if d > dist[u]:
16 continue
17 for v, t in graph[u]:
18 nd = d + t
19 if nd < dist[v]:
20 dist[v] = nd
21 ways[v] = ways[u]
22 heapq.heappush(heap, (nd, v))
23 elif nd == dist[v]:
24 ways[v] = (ways[v] + ways[u]) % MOD
25 return ways[n - 1]1class Solution {
2 public int countPaths(int n, int[][] roads) {
3 final int MOD = 1_000_000_007;
4 List<List<int[]>> graph = new ArrayList<>();
5 for (int i = 0; i < n; i++) graph.add(new ArrayList<>());
6 for (int[] r : roads) {
7 graph.get(r[0]).add(new int[]{r[1], r[2]});
8 graph.get(r[1]).add(new int[]{r[0], r[2]});
9 }
10 long[] dist = new long[n];
11 Arrays.fill(dist, Long.MAX_VALUE);
12 int[] ways = new int[n];
13 dist[0] = 0;
14 ways[0] = 1;
15 PriorityQueue<long[]> heap = new PriorityQueue<>((a, b) -> Long.compare(a[0], b[0]));
16 heap.offer(new long[]{0, 0});
17 while (!heap.isEmpty()) {
18 long[] top = heap.poll();
19 long d = top[0];
20 int u = (int) top[1];
21 if (d > dist[u]) continue;
22 for (int[] e : graph.get(u)) {
23 int v = e[0];
24 long nd = d + e[1];
25 if (nd < dist[v]) {
26 dist[v] = nd;
27 ways[v] = ways[u];
28 heap.offer(new long[]{nd, v});
29 } else if (nd == dist[v]) {
30 ways[v] = (ways[v] + ways[u]) % MOD;
31 }
32 }
33 }
34 return ways[n - 1];
35 }
36}1class Solution {
2public:
3 int countPaths(int n, vector<vector<int>>& roads) {
4 const int MOD = 1000000007;
5 vector<vector<pair<int, int>>> graph(n);
6 for (auto& r : roads) {
7 graph[r[0]].push_back({r[1], r[2]});
8 graph[r[1]].push_back({r[0], r[2]});
9 }
10 vector<long long> dist(n, LLONG_MAX);
11 vector<int> ways(n, 0);
12 dist[0] = 0;
13 ways[0] = 1;
14 priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<>> heap;
15 heap.push({0, 0});
16 while (!heap.empty()) {
17 auto [d, u] = heap.top();
18 heap.pop();
19 if (d > dist[u]) continue;
20 for (auto& [v, t] : graph[u]) {
21 long long nd = d + t;
22 if (nd < dist[v]) {
23 dist[v] = nd;
24 ways[v] = ways[u];
25 heap.push({nd, v});
26 } else if (nd == dist[v]) {
27 ways[v] = (ways[v] + ways[u]) % MOD;
28 }
29 }
30 }
31 return ways[n - 1];
32 }
33};Time and space complexity
O((n + E) log E)
Each road can push at most one heap entry per direction, and each push or pop costs O(log E). The counting adds only constant work per relaxation.
O(n + E)
The adjacency list holds every road twice, the heap holds at most O(E) entries, and dist and ways are O(n).
Other approaches
Dijkstra, then DP over the shortest-path DAG (time O((n + E) log E), space O(n + E))
Compute all distances first, keep only roads with dist[u] + t == dist[v], and count paths in that DAG in order of distance. Same result, two passes instead of one.
Dense Dijkstra with an adjacency matrix (time O(n^2), space O(n^2))
Scan all n nodes for the closest unsettled one instead of using a heap. With n at most 200 this is O(n^2) and works well on dense road maps.
Enumerate all routes with DFS (time O(n!), space O(n))
List every simple path and count those of minimum length. Correct on tiny inputs but exponential in general.
Common mistakes
- Storing distances in 32-bit integers. Totals reach about 2 * 10^11 and overflow, which silently breaks both the comparisons and the count.
- Adding to ways[v] when a strictly shorter time is found. The old count belonged to slower routes and must be replaced, not extended.
- Not skipping stale heap entries. A stale pop would pass along a count from a node using an outdated time.
- Forgetting the modulo when adding counts, or applying it to the distances instead of the counts.
Frequently asked questions
Why is ways[u] final when u is popped?
All road times are positive, so any node before u on a shortest route has a strictly smaller time and was popped earlier. Every contribution to ways[u] has therefore already been added.
Why does a shorter time reset the count instead of adding to it?
The count only covers routes of the current best time. A strictly faster route makes all earlier routes non-shortest, so they no longer count.
Does the modulo affect the comparisons?
No. Only the counts are reduced modulo 10^9 + 7. Distances are compared exactly, which is why they need 64-bit integers.