The n-queens puzzle is the problem of placing n queens on an n x n chessboard
such that no two queens attack each other.
Given an integer n,
return all distinct solutions to the n-queens puzzle. You may return the answer in any order.
Each solution contains a distinct board configuration of the n-queens' placement,
where 'Q' and '.' both indicate a queen and an empty space, respectively.
N-Queen 퍼즐은 n * n 크기의 체스판에 n개의 체스를 두는 방법을 찾는 퍼즐이다.
가능한 모든 경우의 수를 리턴하시오.
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
ans = []
board = [['.'] * n for _ in range(n)]
cols = set()
diag1 = set()
diag2 = set()
def backtracking(row):
if row == n:
ans.append([''.join(i) for i in board])
return
for col in range(n):
if col in cols or row - col in diag1 or row + col in diag2:
continue
cols.add(col)
diag1.add(row - col)
diag2.add(row + col)
board[row][col] = 'Q'
backtracking(row + 1)
cols.remove(col)
diag1.remove(row - col)
diag2.remove(row + col)
board[row][col] = '.'
backtracking(0)
return ans