Problem Description
Given a weighted undirected graph with n intersections (nodes) labeled from 0 to n-1 and a list of roads connecting intersections with associated travel times, determine the number of distinct ways to travel from intersection 0 to intersection n-1 using the shortest possible total travel time. Return the final result modulo 10^9 + 7.
Key Insights
- The problem requires computing the shortest distance from the source (0) to the destination (n-1) in a weighted graph.
- Dijkstra’s algorithm is a natural choice due to non-negative edge weights.
- While computing the shortest distances, maintain a count of how many ways each node can be reached using the minimum time.
- Update the count when a new shorter path is found or when another path leading to the same shortest distance is discovered.
- Always perform modulus operations to handle large numbers.
Space and Time Complexity
Time Complexity: O(E log V), where E is the number of roads and V is the number of intersections. Space Complexity: O(V + E), which accounts for the distance array, ways array, and graph representation.
Solution
We modify Dijkstra's algorithm to not only compute the shortest path but also track the number of ways to reach each intersection using shortest possible travel times. We use:
- A graph represented as an adjacency list.
- A distance array (or vector) initialized with infinity for all nodes except the starting node (set to 0).
- A ways array to count the number of ways to achieve the recorded shortest distance.
- A priority queue (or min-heap) to efficiently fetch the next node with the smallest temporary distance. During the relaxation step for each neighbor, if a shorter path is found, update both the distance and the ways count; if an equally short path is found, add the number of new ways to the count modulo 10^9 + 7.