class Solution:
def solveNQueens(self, n):
def is_valid(row, col, path):
# 检查列
for i in range(row):
if path[i][col] == 'Q':
return False # 当前列已经存在皇后,不合法
# 检查 135 度角是否有皇后
i, j = row - 1, col - 1
while i >= 0 and j >= 0:
if path[i][j] == 'Q':
return False # 左上方向已经存在皇后,不合法
i -= 1
j -= 1
# 检查 45 度角是否有皇后
i, j = row - 1, col + 1
while i >= 0 and j < len(path):
if path[i][j] == 'Q':
return False # 右上方向已经存在皇后,不合法
i -= 1
j += 1
return True # 当前位置合法
def backtracking(path, row):
if row == n:
res.append(path[:])
else:
for col in range(n): # col是列
if is_valid(row, col, path):
path[row] = path[row][:col] + "Q" + path[row][col+1:]
backtracking(path, row+1)
path[row] = path[row][:col] + "." + path[row][col+1:]
res = []
chessboard = ["."*n for _ in range(n)]
row = 0 # 行
backtracking(chessboard, row)
return res
n = 4
print(Solution().solveNQueens(n))
51. N 皇后
最新推荐文章于 2024-10-30 13:16:11 发布