1976. Number of Ways to Arrive at Destination
Description
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] = [ui, vi, timei]
means that there is a road between intersections ui
and vi
that takes timei
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 109 + 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 <= 200
n - 1 <= roads.length <= n * (n - 1) / 2
roads[i].length == 3
0 <= ui, vi <= n - 1
1 <= timei <= 109
ui != vi
- There is at most one road connecting any two intersections.
- You can reach any intersection from any other intersection.
Solutions
Solution 1: Naive Dijkstra Algorithm
We define the following arrays:
g
represents the adjacency matrix of the graph.g[i][j]
represents the shortest path length from pointi
to pointj
. Initially, all are infinity, whileg[0][0]
is 0. Then we traverseroads
and updateg[u][v]
andg[v][u]
tot
.dist[i]
represents the shortest path length from the starting point to pointi
. Initially, all are infinity, whiledist[0]
is 0.f[i]
represents the number of shortest paths from the starting point to pointi
. Initially, all are 0, whilef[0]
is 1.vis[i]
represents whether pointi
has been visited. Initially, all areFalse
.
Then, we use the naive Dijkstra algorithm to find the shortest path length from the starting point to the end point, and record the number of shortest paths for each point during the process.
Finally, we return f[n - 1]
. Since the answer may be very large, we need to take the modulus of $10^9 + 7$.
The time complexity is $O(n^2)$, and the space complexity is $O(n^2)$, where $n$ is the number of points.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
|