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
- 57 lines of Java from the credited upstream file 2867.java.
- The implementation visibly relies on sequence storage.
- 5 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 public long countPaths(int n, int[][] edges) {3 final boolean[] isPrime = sieveEratosthenes(n + 1);4 List<Integer>[] graph = new List[n + 1];5 6 for (int i = 1; i <= n; ++i)7 graph[i] = new ArrayList<>();8 9 for (int[] edge : edges) {10 final int u = edge[0];11 final int v = edge[1];12 graph[u].add(v);13 graph[v].add(u);14 }15 16 dfs(graph, 1, -1, isPrime);17 return ans;18 }19 20 private long ans = 0;21 22 private Pair<Long, Long> dfs(List<Integer>[] graph, int u, int prev, boolean[] isPrime) {23 long countZeroPrimePath = isPrime[u] ? 0 : 1;24 long countOnePrimePath = isPrime[u] ? 1 : 0;25 26 for (final int v : graph[u]) {27 if (v == prev)28 continue;29 Pair<Long, Long> pair = dfs(graph, v, u, isPrime);30 final long countZeroPrimeChildPath = pair.getKey();31 final long countOnePrimeChildPath = pair.getValue();32 ans +=33 countZeroPrimePath * countOnePrimeChildPath + countOnePrimePath * countZeroPrimeChildPath;34 if (isPrime[u]) {35 countOnePrimePath += countZeroPrimeChildPath;36 } else {37 countZeroPrimePath += countZeroPrimeChildPath;38 countOnePrimePath += countOnePrimeChildPath;39 }40 }41 42 return new Pair<>(countZeroPrimePath, countOnePrimePath);43 }44 45 private boolean[] sieveEratosthenes(int n) {46 boolean[] isPrime = new boolean[n];47 Arrays.fill(isPrime, true);48 isPrime[0] = false;49 isPrime[1] = false;50 for (int i = 2; i * i < n; ++i)51 if (isPrime[i])52 for (int j = i * i; j < n; j += i)53 isPrime[j] = false;54 return isPrime;55 }56}57