题解 | #N皇后问题#
N皇后问题
https://www.nowcoder.com/practice/c76408782512486d91eea181107293b6
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param n int整型 the n
# @return int整型
#
class Solution:
def Nqueen(self, n: int) -> int:
# write code here
m = 2 * n - 1
col = [0] * n
ans = []
on_path, diag1, diag2 = [False] * n, [False] * m, [False] * m
def dfs(r: int) -> None:
if r == n:
ans.append(["." * c + "Q" + "." * (n - 1 - c) for c in col])
return
for c, on in enumerate(on_path):
if not on and not diag1[r + c] and not diag2[r - c]:
col[r] = c
on_path[c] = diag1[r + c] = diag2[r - c] = True
dfs(r + 1)
on_path[c] = diag1[r + c] = diag2[r - c] = False # 恢复现场
dfs(0)
return len(ans)


查看14道真题和解析