Approach
Depth-first search
For Number of Valid Move Combinations On Chessboard, 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
- 51 lines of Python from the credited upstream file 2056.py.
- The implementation visibly relies on sequence storage, 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 countCombinations(3 self,4 pieces: list[str],5 positions: list[list[int]],6 ) -> int:7 n = len(pieces)8 moves = {"rook": [(1, 0), (-1, 0), (0, 1), (0, -1)],9 "bishop": [(1, 1), (1, -1), (-1, 1), (-1, -1)],10 "queen": [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1)]}11 hashedBoards = set()12 13 def getHash(board: list[list[int]]) -> Tuple:14 return tuple([tuple(pos) for pos in board])15 16 def dfs(17 board: list[list[int]],18 pieceMoves: list[tuple[int, int]],19 activeMask: int,20 ) -> None:21 """Performs a depth-first search to explore all possible board states."""22 if activeMask == 0:23 return24 hashedBoards.add(getHash(board))25 26 for nextActiveMask in range(1, 1 << n):27 if activeMask & nextActiveMask != nextActiveMask:28 continue29 30 31 nextBoard = [pos.copy() for pos in board]32 33 34 for i in range(n):35 if nextActiveMask >> i & 1:36 nextBoard[i][0] += pieceMoves[i][0]37 nextBoard[i][1] += pieceMoves[i][1]38 39 40 if len(set(getHash(nextBoard))) < n:41 continue42 43 44 if all(1 <= x <= 8 and 1 <= y <= 8 for x, y in nextBoard):45 dfs(nextBoard, pieceMoves, nextActiveMask)46 47 for pieceMoves in itertools.product(*(moves[piece] for piece in pieces)):48 dfs(positions, pieceMoves, (1 << n) - 1)49 50 return len(hashedBoards)51