class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
res = []
board = [['.'] * n for _ in range(n)]
def backtrace(rowIndex: int) -> None:
if(rowIndex == len(board)):
res.append(self.generate(board.copy()))
return
for colIndex in range(len(board)):
if(self.isValid(board, rowIndex, colIndex)):
board[rowIndex][colIndex] = "Q"
backtrace(rowIndex + 1)
board[rowIndex][colIndex] = "."
backtrace(0)
return res
def generate(self, board: List[List[str]]) -> List[str]:
res = []
for tmp in board:
res.append("".join(tmp))
return res
def isValid(self, board: List[List[str]], rowIndex: int, colIndex: int) -> bool:
for i in range(rowIndex):
if board[i][colIndex] == 'Q':
return False
i = rowIndex -1
j = colIndex - 1
while(i >=0 and j >=0):
if board[i][j] == 'Q':
return False
i -= 1
j -= 1
j = colIndex + 1
i = rowIndex - 1
while(i >= 0 and j < len(board)):
if board[i][j] == 'Q':
return False
i -= 1
j += 1
return True
#51. N 皇后
最新推荐文章于 2022-10-13 14:27:29 发布