class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
if not n: return []
chessboard = [['.'] * n for _ in range(n)]
res = []
def isValid(row, col, chessboard):
#检查列
for i in range(len(chessboard)):#这是一个剪枝
if chessboard[i][col] == 'Q':
return False
# 检查 45度角是否有皇后
i = row -1
j = col -1
while i>=0 and j>=0:
if chessboard[i][j] == 'Q':
return False
i -= 1
j -= 1
# 检查 135度角是否有皇后
i = row - 1
j = col + 1
while i>=0 and j < len(chessboard):
if chessboard[i][j] == 'Q':
return False
i -= 1
j += 1
return True
def backtracking(board, row, n):
# 如果走到最后一行,说明已经找到一个解
if row == n:
temp_res = []
for temp in board:
temp_str = "".join(temp)
temp_res.append(temp_str)
res.append(temp_res)
return
for col in range(n):
if not isValid(row, col, board):
continue
board[row][col] = 'Q'
backtracking(board, row+1, n)
board[row][col] = '.'
backtracking(chessboard, 0, n)
return res