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