我们需要准备 3 个 set 来保存已经使用过的列、对角线和反对角线。逻辑比较简单,我们通过代码和注释来理解。
classSolution: defsolveNQueens(self, n: int) -> List[List[str]]: # Prepare the answer list and an empty board in the required format. ans, board = [], [['.'] * n for _ inrange(n)]
defformat(res): """Produce the output to meet to required format.""" out = [] for row in res: out.append(''.join(row)) return out
defsolve(row, cols, diag, anti, res): """Solve recursively.""" # The base case that we know we've got a right answer. if row == n: ans.append(format(res))
# Try each position at this row. for q inrange(n): # Calculate the top point of diagonal and anti-diagonal. d, a = q - row, q + row
# Check if the current place can place a Queen. if q notin cols and d notin diag and a notin anti: cols.add(q) diag.add(d) anti.add(a) res[row][q] = 'Q'