leetcode 每日一题 51. N皇后
回溯法
思路:
参考37.解数独。在约束条件判断中,主对角线row-col = 常数, 副对角线 row+col = 常数。
代码:
class Solution: def solveNQueens(self, n: int) -> List[List[str]]: def could_place(row,col): return not(cols[col]+hill_diagonal[row-col]+dale_diagonal[row+col]) def place_queen(row,col): queens.add((row,col)) cols[col] = 1 hill_diagonal[row-col] = 1 dale_diagonal[row+col] = 1 def remove_queen(row,col): queens.remove((row,col)) cols[col] = 0 hill_diagonal[row-col] = 0 dale_diagonal[row+col] = 0 def add_solution(): solution = [] for _,col in sorted(queens): solution.append('.'*col + 'Q'+'.'*(n-col-1)) res.append(solution) def backtrack(row = 0): for col in range(n): if could_place(row,col): place_queen(row,col) if row + 1 == n: add_solution() else: backtrack(row+1) remove_queen(row,col) cols = [0]*n hill_diagonal = [0]*(2*n-1) dale_diagonal = [0]*(2*n-1) queens = set() res = [] backtrack() return res