My sol:
python
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
ans = []
col = [0] * n
def valid(r, c):
for R in range(r):
C = col[R]
if r + c == R + C or r - c == R - C:
return False
return True
# s means the available column
def dfs(r, s):
if r == n:
ans.append(['.' * col[r] + 'Q' + '.' * (n - col[r] - 1) for r in range(r)])
return
for c in s:
if valid(r, c):
col[r] = c
dfs(r+1, s-{c})
dfs(0, set(range(n)))
return ans
python
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
ans = []
queens = [0] * n # 皇后放在 (r,queens[r])
col = [False] * n
diag1 = [False] * (n * 2 - 1)
diag2 = [False] * (n * 2 - 1)
def dfs(r: int) -> None:
if r == n:
ans.append(['.' * c + 'Q' + '.' * (n - 1 - c) for c in queens])
return
# 在 (r,c) 放皇后
for c, ok in enumerate(col):
if not ok and not diag1[r + c] and not diag2[r - c]: # 判断能否放皇后
queens[r] = c # 直接覆盖,无需恢复现场
col[c] = diag1[r + c] = diag2[r - c] = True # 皇后占用了 c 列和两条斜线
dfs(r + 1)
col[c] = diag1[r + c] = diag2[r - c] = False # 恢复现场
dfs(0)
return ans
作者:灵茶山艾府
链接:https://leetcode.cn/problems/n-queens/solutions/2079586/hui-su-tao-lu-miao-sha-nhuang-hou-shi-pi-mljv/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。