Approach
Depth-first search
For Count Valid Paths in a Tree, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 42 lines of Python from the credited upstream file 2867.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 def countPaths(self, n: int, edges: list[list[int]]) -> int:3 ans = 04 isPrime = self._sieveEratosthenes(n + 1)5 graph = [[] for _ in range(n + 1)]6 7 for u, v in edges:8 graph[u].append(v)9 graph[v].append(u)10 11 def dfs(u: int, prev: int) -> tuple[int, int]:12 nonlocal ans13 countZeroPrimePath = int(not isPrime[u])14 countOnePrimePath = int(isPrime[u])15 16 for v in graph[u]:17 if v == prev:18 continue19 countZeroPrimeChildPath, countOnePrimeChildPath = dfs(v, u)20 ans += (countZeroPrimePath * countOnePrimeChildPath +21 countOnePrimePath * countZeroPrimeChildPath)22 if isPrime[u]:23 countOnePrimePath += countZeroPrimeChildPath24 else:25 countZeroPrimePath += countZeroPrimeChildPath26 countOnePrimePath += countOnePrimeChildPath27 28 return countZeroPrimePath, countOnePrimePath29 30 dfs(1, -1)31 return ans32 33 def _sieveEratosthenes(self, n: int) -> list[bool]:34 isPrime = [True] * n35 isPrime[0] = False36 isPrime[1] = False37 for i in range(2, int(n**0.5) + 1):38 if isPrime[i]:39 for j in range(i * i, n, i):40 isPrime[j] = False41 return isPrime42