mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
Update 0051.N皇后.md
This commit is contained in:
@ -348,48 +348,47 @@ class Solution {
|
|||||||
```python
|
```python
|
||||||
class Solution:
|
class Solution:
|
||||||
def solveNQueens(self, n: int) -> List[List[str]]:
|
def solveNQueens(self, n: int) -> List[List[str]]:
|
||||||
if not n: return []
|
result = [] # 存储最终结果的二维字符串数组
|
||||||
board = [['.'] * n for _ in range(n)]
|
|
||||||
res = []
|
chessboard = ['.' * n for _ in range(n)] # 初始化棋盘
|
||||||
def isVaild(board,row, col):
|
self.backtracking(n, 0, chessboard, result) # 回溯求解
|
||||||
#判断同一列是否冲突
|
return [[''.join(row) for row in solution] for solution in result] # 返回结果集
|
||||||
for i in range(len(board)):
|
|
||||||
if board[i][col] == 'Q':
|
def backtracking(self, n: int, row: int, chessboard: List[str], result: List[List[str]]) -> None:
|
||||||
return False
|
if row == n:
|
||||||
# 判断左上角是否冲突
|
result.append(chessboard[:]) # 棋盘填满,将当前解加入结果集
|
||||||
i = row -1
|
return
|
||||||
j = col -1
|
|
||||||
while i>=0 and j>=0:
|
for col in range(n):
|
||||||
if board[i][j] == 'Q':
|
if self.isValid(row, col, chessboard):
|
||||||
return False
|
chessboard[row] = chessboard[row][:col] + 'Q' + chessboard[row][col+1:] # 放置皇后
|
||||||
i -= 1
|
self.backtracking(n, row + 1, chessboard, result) # 递归到下一行
|
||||||
j -= 1
|
chessboard[row] = chessboard[row][:col] + '.' + chessboard[row][col+1:] # 回溯,撤销当前位置的皇后
|
||||||
# 判断右上角是否冲突
|
|
||||||
i = row - 1
|
def isValid(self, row: int, col: int, chessboard: List[str]) -> bool:
|
||||||
j = col + 1
|
# 检查列
|
||||||
while i>=0 and j < len(board):
|
for i in range(row):
|
||||||
if board[i][j] == 'Q':
|
if chessboard[i][col] == 'Q':
|
||||||
return False
|
return False # 当前列已经存在皇后,不合法
|
||||||
i -= 1
|
|
||||||
j += 1
|
# 检查 45 度角是否有皇后
|
||||||
return True
|
i, j = row - 1, col - 1
|
||||||
|
while i >= 0 and j >= 0:
|
||||||
|
if chessboard[i][j] == 'Q':
|
||||||
|
return False # 左上方向已经存在皇后,不合法
|
||||||
|
i -= 1
|
||||||
|
j -= 1
|
||||||
|
|
||||||
|
# 检查 135 度角是否有皇后
|
||||||
|
i, j = row - 1, 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)
|
|
||||||
for col in range(n):
|
|
||||||
if not isVaild(board, row, col):
|
|
||||||
continue
|
|
||||||
board[row][col] = 'Q'
|
|
||||||
backtracking(board, row+1, n)
|
|
||||||
board[row][col] = '.'
|
|
||||||
backtracking(board, 0, n)
|
|
||||||
return res
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user