Number of Restricted Paths From First to Last Node — LeetCode 1786 Python Solution
- Problem
- #1786
- Pattern
- Topological Sort
- Reading time
- 5 min
- Source
- leetcode.com
The problem
There is an undirected weighted connected graph. You are given a positive integer n which denotes that the graph has n nodes labeled from 1 to n, and an array edges where each edges[i] = [ui, vi, weighti] denotes that there is an edge between nodes ui and vi with weight equal to weighti.
Example
- Input
- n = 5, edges = [[1,2,3],[1,3,3],[2,3,1],[1,4,2],[5,2,2],[3,5,1],[5,4,10]]
- Output
- 3
- Explanation
- Each circle contains the node number in black and its distanceToLastNode value in blue. The three restricted paths are:
Python solution
class Solution:
def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:
@cache
def dfs(i):
if i == n:
return 1
ans = 0
for j, _ in g[i]:
if dist[i] > dist[j]:
ans = (ans + dfs(j)) % mod
return ans
g = defaultdict(list)
for u, v, w in edges:
g[u].append((v, w))
g[v].append((u, w))
q = [(0, n)]
dist = [inf] * (n + 1)
dist[n] = 0
mod = 10**9 + 7
while q:
_, u = heappop(q)
for v, w in g[u]:
if dist[v] > dist[u] + w:
dist[v] = dist[u] + w
heappush(q, (dist[v], v))
return dfs(1)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n·m) (typical) |
| Space | O(n·m) or optimized auxiliary |
Pattern: Topological Sort
Order a set of tasks so that every dependency comes before the thing that needs it. LeetCode 1786. Number of Restricted Paths From First to Last Node is filed here because LeetCode tags it Topological Sort, which is the vocabulary this hub collects.
The topological sort guide has the Python template for the pattern and the 32 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1786. Number of Restricted Paths From First to Last Node?
- LeetCode 1786. Number of Restricted Paths From First to Last Node is rated Medium on LeetCode.
- What topics does LeetCode 1786. Number of Restricted Paths From First to Last Node cover?
- LeetCode 1786. Number of Restricted Paths From First to Last Node is tagged Graph, Topological Sort, Dynamic Programming, Shortest Path and Heap (Priority Queue) on LeetCode.