52. N皇后 II
https://leetcode-cn.com/problems/n-queens-ii/
解法一:
与51题类似,在其基础上,依然是回溯,每次找到的时候全局计数器+1即可。
class Solution:
def totalNQueens(self, n: int) -> int:
self.count = 0 #全局计数
board = [['.'] * n for _ in range(n)] #注意二维列表的创建方式
self.solve(board, 0, n)
return self.count
def solve(self, board, i, n):
if i == n: #来到最后一行,得到一个结果
self.count += 1
for j in range(n):
if self.isValid(board, i, j, n): #若合法则填入,并递归进入下一行
board[i][j] = 'Q'
self.solve(board, i+1, n)
board[i][j] = '.' #还原现场
def isValid(self, board, row, col, n): #判断row,col位置是否合法
#判断同一列
for i in range(row-1, -1, -1):
if board[i][col] == 'Q':
return False
#判断左上方向
for i, j in zip(range(row - 1, -1, -1), range(col - 1, -1, -1)):
if board[i][j] == 'Q':
return False
#判断右上方向
for i, j in zip(range(row - 1, -1, -1), range(col + 1, n)):
if board[i][j] == 'Q':
return False
return True
最后更新于