-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0052-n-queens-ii.py
More file actions
47 lines (38 loc) · 1.34 KB
/
0052-n-queens-ii.py
File metadata and controls
47 lines (38 loc) · 1.34 KB
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
# time complexity: O(n!)
# space complexity: O(n)
from typing import List
class Solution:
def totalNQueens(self, n: int) -> int:
result = []
emptyBoard = [["."] * n for _ in range(n)]
def backtrack(r: int, diagonals: set, antiDiagonals: set, cols: set, state: List[str]):
if r == n:
board = []
for row in state:
board.append("".join(row))
result.append(board)
return
for c in range(n):
currDiagonal = r - c
currAntiDiagonal = r + c
if (
c in cols
or currDiagonal in diagonals
or currAntiDiagonal in antiDiagonals
):
continue
cols.add(c)
diagonals.add(currDiagonal)
antiDiagonals.add(currAntiDiagonal)
state[r][c] = "Q"
backtrack(r + 1, diagonals, antiDiagonals, cols, state)
cols.remove(c)
diagonals.remove(currDiagonal)
antiDiagonals.remove(currAntiDiagonal)
state[r][c] = "."
backtrack(0, set(), set(), set(), emptyBoard)
return len(result)
n = 4
print(Solution().totalNQueens(n))
n = 1
print(Solution().totalNQueens(n))