-
-
Notifications
You must be signed in to change notification settings - Fork 38
/
0052-n-queens-ii.py
51 lines (40 loc) · 1.48 KB
/
0052-n-queens-ii.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
# time complexity: O(n!)
# space complexity: O(n)
from typing import List
class Solution:
def totalNQueens(self, n: int) -> int:
return len(self.solveNQueens(n))
def solveNQueens(self, n: int) -> List[List[str]]:
def createBoard(state: List[str]):
board = []
for row in state:
board.append("".join(row))
return board
def backtrack(row: int, diagonals: set, antiDiagonals: set, cols: set, state: List[str]):
if row == n:
ans.append(createBoard(state))
return
for col in range(n):
currDiagonal = row - col
currAntiDiagonal = row + col
if (
col in cols
or currDiagonal in diagonals
or currAntiDiagonal in antiDiagonals
):
continue
cols.add(col)
diagonals.add(currDiagonal)
antiDiagonals.add(currAntiDiagonal)
state[row][col] = "Q"
backtrack(row + 1, diagonals, antiDiagonals, cols, state)
cols.remove(col)
diagonals.remove(currDiagonal)
antiDiagonals.remove(currAntiDiagonal)
state[row][col] = "."
ans = []
emptyBoard = [["."] * n for _ in range(n)]
backtrack(0, set(), set(), set(), emptyBoard)
return ans
n = 4
print(Solution().totalNQueens(n))