Problem Description
Given an undirected weighted connected graph with n nodes (labeled 1 to n) and an edge list where each edge connects two nodes with a given weight, determine the number of restricted paths from node 1 to node n. A restricted path is defined as a path where for every consecutive pair of nodes in the path, the shortest distance (using edge weights) from the current node to node n is strictly greater than that from the next node to node n. Return the count modulo 10^9 + 7.
Key Insights
- Use Dijkstra's algorithm starting from node n to compute the shortest distance from every node to node n.
- A restricted path can only move in the direction of strictly decreasing distance values, forming a kind of “topological” order.
- Dynamic Programming (or DFS with memoization) can be used to count the number of valid paths from node 1 to node n.
- Modulo arithmetic (MOD = 10^9 + 7) must be applied to handle large counts.
Space and Time Complexity
Time Complexity: O(E log N) for Dijkstra's algorithm + O(N + E) for the DP/DFS traversal, overall O(E log N). Space Complexity: O(N + E) for storing the graph and additional data structures for distances and memoization.
Solution
We first run Dijkstra's algorithm from the destination node n to calculate the shortest distance from every node to node n. With these distances, we can then perform a DFS (or iterative DP) starting from node 1. During this DFS, for each node we traverse only those neighbors that have a strictly smaller distance to node n than the current node. We memoize each count to avoid redundant computations. The result is then returned modulo 10^9 + 7.