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 modulo10^9 + 7.
graph TD
A(0)
B(1)
C(2)
D(3)
E(4)
F(5)
G(6)
A ---|5| E
A ---|7| G
A ---|2| B
B ---|3| C
B ---|3| D
G ---|3| D
D ---|1| F
G ---|1| F
C ---|1| F
E ---|2| G
1
2
3
4
5
6
7
8
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: 4Explanation: The shortest amount of time it takes to go from intersection 0 to intersection 6is7 minutes.The four ways to get there in7 minutes are:-0➝6-0➝4➝6-0➝1➝2➝5➝6-0➝1➝3➝5➝6
Example 2:
1
2
3
Input: n =2, roads =[[1,0,10]]Output: 1Explanation: 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 <= 10^9
ui != vi
There is at most one road connecting any two intersections.
You can reach any intersection from any other intersection.
To solve this problem, we aim to compute the number of ways to reach intersection n-1 from 0 using the shortest time possible. This involves using Dijkstra’s algorithm to find the shortest path and counting the number of paths that result in the shortest time.
classSolution:
defcountPaths(self, n: int, roads: List[List[int]]) -> int:
MOD =10**9+7# Build graph as adjacency list graph = [[] for _ in range(n)]
for u, v, time in roads:
graph[u].append((v, time))
graph[v].append((u, time))
# Initialise distances and ways arrays dist = [float('inf')] * n
ways = [0] * n
dist[0] =0 ways[0] =1# Priority queue for Dijkstra's algorithm pq = [(0, 0)] # (distance, node)while pq:
time, node = heapq.heappop(pq)
# Skip outdated distance recordsif time > dist[node]:
continue# Process neighboursfor neighbor, travel_time in graph[node]:
new_time = time + travel_time
# Found a shorter pathif new_time < dist[neighbor]:
dist[neighbor] = new_time # Update the shortest distance ways[neighbor] = ways[node] # Inherit the number of ways heapq.heappush(pq, (new_time, neighbor))
# Found an alternate path with the same shortest distanceelif new_time == dist[neighbor]:
ways[neighbor] = (ways[neighbor] + ways[node]) % MOD # Accumulate the number of ways# Return number of ways to reach the last nodereturn ways[n -1]