Number of Ways to Arrive at Destination Problem
Description
LeetCode Problem 1976.
You are in a city that consists of n intersections numbered from 0 to n - 1 with bi-directional roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two intersections.
You are given an integer n and a 2D integer array roads where roads[i] = [u_i, v_i, time_i] means that there is a road between intersections u_i and v_i that takes time_i minutes to travel. You want to know in how many ways you can travel from intersection 0 to intersection n - 1 in the shortest amount of time.
Return the number of ways you can arrive at your destination 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
Explanation: The shortest amount of time it takes to go from intersection 0 to intersection 6 is 7 minutes.
The four ways to get there in 7 minutes are:
- 0 ➝ 6
- 0 ➝ 4 ➝ 6
- 0 ➝ 1 ➝ 2 ➝ 5 ➝ 6
- 0 ➝ 1 ➝ 3 ➝ 5 ➝ 6
Example 2:
Input: n = 2, roads = [[1,0,10]]
Output: 1
Explanation: There is only one way to go from intersection 0 to intersection 1, and it takes 10 minutes.
Constraints:
1 <= n <= 200n - 1 <= roads.length <= n * (n - 1) / 2roads[i].length == 30 <= u_i, v_i <= n - 11 <= time_i <= 10^9u_i!= v_i- There is at most one road connecting any two intersections.
- You can reach any intersection from any other intersection.
Solution
Approach: Dijkstra with a Path Count
Keep four things: an adjacency matrix g of road times, dist[i] for the shortest time from intersection 0, f[i] for the number of shortest paths to i (with f[0] = 1), and vis[i] for finalized intersections.
Run the simple O(n^2) Dijkstra: pick the unvisited intersection t with the smallest dist, and relax every neighbor j. If dist[t] + g[t][j] is smaller than dist[j], set dist[j] to it and copy f[t] into f[j]; if it is equal, add f[t] to f[j] modulo 10^9 + 7.
The answer is f[n - 1].
Complexity: time O(n^2), space O(n^2), where n is the number of intersections.
class Solution:
def countPaths(self, n: int, roads: List[List[int]]) -> int:
g = [[float("inf")] * n for _ in range(n)]
for u, v, t in roads:
g[u][v] = g[v][u] = t
g[0][0] = 0
dist = [float("inf")] * n
dist[0] = 0
f = [0] * n
f[0] = 1
vis = [False] * n
for _ in range(n):
t = -1
for j in range(n):
if not vis[j] and (t == -1 or dist[j] < dist[t]):
t = j
vis[t] = True
for j in range(n):
if j == t:
continue
ne = dist[t] + g[t][j]
if dist[j] > ne:
dist[j] = ne
f[j] = f[t]
elif dist[j] == ne:
f[j] += f[t]
mod = 10**9 + 7
return f[-1] % mod