-
Notifications
You must be signed in to change notification settings - Fork 17
/
n-queens.py
63 lines (50 loc) · 1.58 KB
/
n-queens.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
from typing import List
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
diag_pos_set = set()
diag_neg_set = set()
cols_set = set()
board = [[False] * n for _ in range(n)]
result = []
def place_queen(row):
if row == n:
result.append([
"".join("Q" if c else "." for c in row)
for row in board
])
else:
for col in range(n):
if not (
row + col in diag_pos_set or \
row - col in diag_neg_set or \
col in cols_set
):
diag_pos_set.add(row + col)
diag_neg_set.add(row - col)
cols_set.add(col)
board[row][col] = True
place_queen(row + 1)
diag_pos_set.discard(row + col)
diag_neg_set.discard(row - col)
cols_set.discard(col)
board[row][col] = False
place_queen(0)
return result
class TestSolution:
def setup(self):
self.sol = Solution()
def test_case1(self):
assert self.sol.solveNQueens(4) == [
[
".Q..",
"...Q",
"Q...",
"..Q."
],
[
"..Q.",
"Q...",
"...Q",
".Q.."
]
]