Approach
Depth-first search
For Count Number of Possible Root Nodes, 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
- 67 lines of Java from the credited upstream file 2581.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 6 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 int rootCount(int[][] edges, int[][] guesses, int k) {3 final int n = edges.length + 1;4 List<Integer>[] graph = new List[n];5 Set<Integer>[] guessGraph = new Set[n];6 int[] parent = new int[n];7 8 for (int i = 0; i < n; ++i) {9 graph[i] = new ArrayList<>();10 guessGraph[i] = new HashSet<>();11 }12 13 for (int[] edge : edges) {14 final int u = edge[0];15 final int v = edge[1];16 graph[u].add(v);17 graph[v].add(u);18 }19 20 for (int[] guess : guesses) {21 final int u = guess[0];22 final int v = guess[1];23 guessGraph[u].add(v);24 }25 26 27 dfs(graph, 0, -1, parent);28 29 30 int correctGuess = 0;31 for (int i = 1; i < n; ++i)32 if (guessGraph[parent[i]].contains(i))33 ++correctGuess;34 35 reroot(graph, 0, -1, correctGuess, guessGraph, k);36 return ans;37 }38 39 private int ans = 0;40 41 private void dfs(List<Integer>[] graph, int u, int prev, int[] parent) {42 parent[u] = prev;43 for (final int v : graph[u])44 if (v != prev)45 dfs(graph, v, u, parent);46 }47 48 private void reroot(List<Integer>[] graph, int u, int prev, int correctGuess,49 Set<Integer>[] guessGraph, int k) {50 if (u != 0) {51 52 53 if (guessGraph[u].contains(prev))54 ++correctGuess;55 56 57 if (guessGraph[prev].contains(u))58 --correctGuess;59 }60 if (correctGuess >= k)61 ++ans;62 for (final int v : graph[u])63 if (v != prev)64 reroot(graph, v, u, correctGuess, guessGraph, k);65 }66}67