Number of Valid Move Combinations On Chessboard LeetCode solution in Python

1
class Solution:
2
def countCombinations(self, pieces: List[str], positions: List[List[int]]) -> int:
3
board = [[set() for _ in range(8)] for _ in range(8)]
4
n = len(pieces)
5
for pos in positions:
6
pos[0] -= 1
7
pos[1] -= 1
8
all_time = set(range(1, 8))
9

10
def recur(i):
11
if i == n:
12
return 1
13
ans = 0
14
line = [(0, 1), (1, 0), (0, -1), (-1, 0)]
15
diag = [(1, 1), (1, -1), (-1, 1), (-1, -1)]
16
r, c = positions[i]
17
if not board[r][c] & all_time:
18
board[r][c] |= all_time
19
ans += recur(i + 1)
20
board[r][c].clear()
21
directions = []
22
if pieces[i] in ("queen", "rook"):
23
directions.extend(line)
24
if pieces[i] in ("queen", "bishop"):
25
directions.extend(diag)
26
for dr, dc in directions:
27
x, y = r + dr, c + dc
28
count = 1
29
while 0 <= x < 8 and 0 <= y < 8 and count not in board[x][y]:
30
board[x][y].add(count)
31
count += 1
32
rest = set(range(count, 8))
33
if not board[x][y] & rest:
34
board[x][y] |= rest
35
ans += recur(i + 1)
36
board[x][y] -= rest
37
x += dr
38
y += dc
39
count -= 1
40
x -= dr
41
y -= dc
42
while count:
43
board[x][y].remove(count)
44
count -= 1
45
x -= dr
46
y -= dc
47
return ans
48

49
return recur(0)

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0