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
- 55 lines of Java from the credited upstream file 488.java.
- The implementation visibly relies on hash lookup, ordered 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 int findMinStep(String board, String hand) {3 Map<String, Integer> mem = new HashMap<>();4 final int ans = dfs(board + '#', hand, mem);5 return ans == Integer.MAX_VALUE ? -1 : ans;6 }7 8 private int dfs(String board, final String hand, Map<String, Integer> mem) {9 final String hashKey = board + '#' + hand;10 if (mem.containsKey(hashKey))11 return mem.get(hashKey);12 board = deDup(board);13 if (board.equals("#"))14 return 0;15 16 Set<Character> boardSet = new HashSet<>();17 for (final char c : board.toCharArray())18 boardSet.add(c);19 20 StringBuilder sb = new StringBuilder();21 for (final char h : hand.toCharArray())22 if (boardSet.contains(h))23 sb.append(h);24 final String hs = sb.toString();25 if (sb.length() == 0) 26 return Integer.MAX_VALUE;27 28 int ans = Integer.MAX_VALUE;29 30 for (int i = 0; i < board.length(); ++i)31 for (int j = 0; j < hs.length(); ++j) {32 33 final String newHand = hs.substring(0, j) + hs.substring(j + 1);34 String newBoard = board.substring(0, i) + hs.charAt(j) + board.substring(i);35 final int res = dfs(newBoard, newHand, mem);36 if (res < Integer.MAX_VALUE)37 ans = Math.min(ans, 1 + res);38 }39 40 mem.put(hashKey, ans);41 return ans;42 }43 44 private String deDup(String board) {45 int start = 0; 46 for (int i = 0; i < board.length(); ++i)47 if (board.charAt(i) != board.charAt(start)) {48 if (i - start >= 3)49 return deDup(board.substring(0, start) + board.substring(i));50 start = i; 51 }52 return board;53 }54}55