2n皇后问题 python 通俗易懂 小白写出来的
n=int(input())
ans=[]
posw=[0]*n
posb=[0]*n
for i in range(n):
ans.append(input().split())
count=0
def checkw(cur):
for i in range(cur):
if posw[i]==posw[cur] or abs(i-cur)==abs(posw[i]-posw[cur]):
return 1
return 0
def checkb(cur):
for i in range(cur):
if posb[i]==posb[cur] or abs(i-cur)==abs(posb[i]-posb[cur]):
return 1
return 0
def dfsw(cur):
if cur==n:
dfsb(0)
return
for i in range(n):
if ans[i][cur]=="0":
continue
posw[cur]=i
if checkw(cur)==0:
dfsw(cur+1)
def dfsb(cur):
global count
if cur==n:
count+=1
return
for i in range(n):
if ans[i][cur]=="0":
continue
if posw[cur]==i:
continue
posb[cur]=i
if checkb(cur)==0:
dfsb(cur+1)
dfsw(0)
print(count)
|