题解 | #N皇后问题#
N皇后问题
https://www.nowcoder.com/practice/c76408782512486d91eea181107293b6
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param n int整型 the n # @return int整型 # class Solution: def __init__(self): self.count = 0 def Nqueen(self , n: int) -> int: # write code here rec = set()#被占用列 rec2 = set()#被占用斜线1 rec3 = set()#被占用斜线2 def check(i,j): if j in rec or i+j in rec2 or i-j in rec3: return False return True def dfs(index): for i in range(index,n): for j in range(n): if check(i,j): rec.add(j) rec2.add(i+j) rec3.add(i-j) if dfs(i+1): self.count+=1 rec.remove(j) rec2.remove(i+j) rec3.remove(i-j) else: continue return False return True dfs(0) return self.count