Approach
Depth-first search
For Zuma Game, 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
- 53 lines of C++ from the credited upstream file 488.cpp.
- The implementation visibly relies on hash lookup.
- 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.
1class Solution {2 public:3 int findMinStep(string board, string hand) {4 const int ans = dfs(board + "#", hand, {});5 return ans == INT_MAX ? -1 : ans;6 }7 8 private:9 int dfs(string&& board, const string& hand,10 unordered_map<string, int>&& mem) {11 const string hashKey = board + '#' + hand;12 if (const auto it = mem.find(hashKey); it != mem.cend())13 return it->second;14 board = deDup(board);15 if (board == "#")16 return 0;17 18 unordered_set<char> boardSet = unordered_set(board.begin(), board.end());19 20 string hs; 21 for (const char h : hand)22 if (boardSet.contains(h))23 hs += h;24 if (hs.empty()) 25 return INT_MAX;26 27 int ans = INT_MAX;28 29 for (int i = 0; i < board.size(); ++i)30 for (int j = 0; j < hs.size(); ++j) {31 32 const string& newHand = hs.substr(0, j) + hs.substr(j + 1);33 string newBoard = board.substr(0, i) + hs[j] + board.substr(i);34 const int res = dfs(std::move(newBoard), newHand, std::move(mem));35 if (res < INT_MAX)36 ans = min(ans, 1 + res);37 }38 39 return mem[hashKey] = ans;40 }41 42 string deDup(string board) {43 int start = 0; 44 for (int i = 0; i < board.size(); ++i)45 if (board[i] != board[start]) {46 if (i - start >= 3)47 return deDup(board.substr(0, start) + board.substr(i));48 start = i; 49 }50 return board;51 }52};53