#2056

Number of Valid Move Combinations On Chessboard

Hard
ArrayStringBacktrackingSimulationBacktrackingSimulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Instead of generating all combinations, we can simulate the movements of the pieces and track their positions using a set to ensure no collisions occur. This is more efficient as it avoids redundant checks.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a set to track occupied positions on the board.
  2. 2Step 2: For each piece, calculate its potential moves and check if they collide with already occupied positions.
  3. 3Step 3: Count valid combinations based on non-collision moves.
solution.py34 lines
1def count_valid_combinations_optimized(pieces, positions):
2    from itertools import product
3    valid_count = 0
4    n = len(pieces)
5    occupied = set()
6
7    def generate_moves(piece, position):
8        moves = []
9        r, c = position
10        if piece == 'rook':
11            for i in range(1, 9):
12                moves.append((r, i))
13                moves.append((i, c))
14        elif piece == 'queen':
15            for i in range(1, 9):
16                moves.append((r, i))
17                moves.append((i, c))
18                moves.append((r + i, c + i))
19                moves.append((r + i, c - i))
20                moves.append((r - i, c + i))
21                moves.append((r - i, c - i))
22        elif piece == 'bishop':
23            for i in range(1, 9):
24                moves.append((r + i, c + i))
25                moves.append((r + i, c - i))
26                moves.append((r - i, c + i))
27                moves.append((r - i, c - i))
28        return moves
29
30    for combination in product(*[generate_moves(pieces[i], positions[i]) for i in range(n)]):
31        if len(set(combination)) == len(combination):
32            valid_count += 1
33    return valid_count
34

Complexity note: The time complexity is O(n) as we only iterate through the pieces and their moves once, while the space complexity is O(n) due to the storage of occupied positions.

  • 1Understanding piece movement is crucial.
  • 2Simulating moves helps avoid collisions.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.