Approach
Depth-first search
For Count Ways to Build Rooms in an Ant Colony, 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
- 65 lines of C++ from the credited upstream file count-ways-to-build-rooms-in-an-ant-colony.cpp.
- The implementation visibly relies on sequence storage.
- 4 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.
123 4class Solution {5public:6 int waysToBuildRooms(vector<int>& prevRoom) {7 vector<vector<int>> adj(size(prevRoom));8 for (int i = 1; i < size(prevRoom); ++i) {9 adj[prevRoom[i]].emplace_back(i);10 }11 return dfs(adj, 0).first;12 }13 14private:15 pair<int, int> dfs(const vector<vector<int>>& adj, int curr) {16 static const int MOD = 1e9 + 7;17 int total_ways = 1, total_cnt = 0;18 for (const auto& child : adj[curr]) {19 const auto& [ways, cnt] = dfs(adj, child);20 total_cnt += cnt;21 total_ways = mulmod(mulmod(total_ways, ways, MOD), nCr(total_cnt, cnt, MOD), MOD);22 }23 return {total_ways, total_cnt + 1};24 }25 26 int nCr(int n, int k, uint32_t mod) {27 while (size(inv_) <= n) { 28 fact_.emplace_back(mulmod(fact_.back(), size(inv_), mod));29 inv_.emplace_back(mulmod(inv_[mod % size(inv_)], mod - mod / size(inv_), mod)); 30 inv_fact_.emplace_back(mulmod(inv_fact_.back(), inv_.back(), mod));31 }32 return mulmod(mulmod(fact_[n], inv_fact_[n - k], mod), inv_fact_[k], mod);33 }34 35 uint32_t addmod(uint32_t a, uint32_t b, uint32_t mod) { 36 a %= mod, b %= mod;37 if (mod - a <= b) {38 b -= mod; 39 }40 return a + b;41 }42 43 44 uint32_t mulmod(uint32_t a, uint32_t b, uint32_t mod) { 45 a %= mod, b %= mod;46 uint32_t result = 0;47 if (a < b) {48 swap(a, b);49 }50 while (b > 0) { 51 if (b % 2 == 1) {52 result = addmod(result, a, mod);53 }54 a = addmod(a, a, mod);55 b /= 2; 56 } 57 return result; 58 }59 60 static const int MOD = 1e9 + 7;61 vector<int> fact_ = {1, 1};62 vector<int> inv_ = {0, 1};63 vector<int> inv_fact_ = {1, 1};64};65