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
- 37 lines of Python from the credited upstream file 488.py.
- The implementation visibly relies on ordered lookup.
- No explicit 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 def findMinStep(self, board: str, hand: str) -> int:3 def deDup(board):4 start = 0 5 for i, c in enumerate(board):6 if c != board[start]:7 if i - start >= 3:8 return deDup(board[:start] + board[i:])9 start = i 10 return board11 12 @functools.lru_cache(None)13 def dfs(board: str, hand: str):14 board = deDup(board)15 if board == '#':16 return 017 18 boardSet = set(board)19 20 hand = ''.join(h for h in hand if h in boardSet)21 if not hand: 22 return math.inf23 24 ans = math.inf25 26 for i in range(len(board)):27 for j, h in enumerate(hand):28 29 newHand = hand[:j] + hand[j + 1:]30 newBoard = board[:i] + h + board[i:]31 ans = min(ans, 1 + dfs(newBoard, newHand))32 33 return ans34 35 ans = dfs(board + '#', hand)36 return -1 if ans == math.inf else ans37