Leetcode 1976: Number of Ways to Arrive at Destination

grid47
grid47
Exploring patterns and algorithms
Apr 23, 2024 8 min read

You are in a city with n intersections, and roads connecting them with specific travel times. Your task is to find the number of different ways you can travel from intersection 0 to intersection n-1 in the shortest time possible. Since the result could be large, return it modulo (10^9 + 7).
Problem
Approach
Steps
Complexity
Input: The input consists of an integer `n` (the number of intersections) and a 2D integer array `roads` where each road is represented by three integers `[u, v, time]`, indicating a road between intersection `u` and `v` that takes `time` minutes to travel.
Example: n = 4, roads = [[0, 1, 1], [1, 2, 1], [2, 3, 1], [0, 2, 2], [1, 3, 2]]
Constraints:
• 1 <= n <= 200
• n - 1 <= roads.length <= n * (n - 1) / 2
• 0 <= ui, vi <= n - 1
• 1 <= time <= 10^9
• ui != vi
• There is at most one road between any two intersections
• You can reach any intersection from any other intersection
Output: The output should be a single integer, representing the number of different ways to travel from intersection 0 to intersection n-1 using the shortest time. The answer should be returned modulo (10^9 + 7).
Example: Output: 2
Constraints:
• The result should be an integer.
Goal: Find the number of ways to travel from intersection 0 to intersection n-1 in the shortest time.
Steps:
• Step 1: Build a graph where each node represents an intersection and each edge represents a road with a time cost.
• Step 2: Use Dijkstra's algorithm to find the shortest time to reach all intersections from intersection 0.
• Step 3: Track the number of ways to reach each intersection with the shortest time, updating the count whenever a shorter path is found or an equal-length path is discovered.
• Step 4: Return the number of ways to reach intersection n-1, modulo (10^9 + 7).
Goal: The solution must be efficient enough to handle the problem's constraints.
Steps:
• The matrix size `n` can be as large as 200.
• The number of roads can be as large as ( n(n - 1)/2 ), so the solution must be optimized.
Assumptions:
• The graph is connected, meaning there's always a path from intersection 0 to intersection n-1.
• There is only one road between any two intersections.
Input: Input: n = 4, roads = [[0, 1, 1], [1, 2, 1], [2, 3, 1], [0, 2, 2], [1, 3, 2]]
Explanation: In this case, the shortest time to go from intersection 0 to intersection 3 is 3 minutes, and there are two ways to achieve this: [0 -> 1 -> 2 -> 3] and [0 -> 2 -> 3].

Input: Input: n = 3, roads = [[0, 1, 5], [1, 2, 10]]
Explanation: In this case, the only possible way to go from intersection 0 to intersection 2 takes 15 minutes: [0 -> 1 -> 2].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus