本文主要是介绍位运算解决八皇后,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
def queenSettle(row,colomn,pie,na):
global count
if row == N:
count += 1
return
bits = (~(colomn | pie | na)) & ((1 << N)-1)
while bits > 0:
p = bits & -bits
queenSettle(row+1,colomn | p,(pie | p) >> 1,(na | p) << 1)
bits = bits & (bits-1)
count = 0
N = 13
queenSettle(0,0,0,0)
print(count)
def DFS(row, shu, pie, na):
global count
bits = ((1 << n) - 1) & ~(shu | pie | na) # 当前行还能放置皇后的列
while bits: # 枚举可用的列
p = bits & -bits
bits ^= p
if row == n - 1:
count += 1
else:
DFS(row + 1, shu | p, (pie | p) >> 1, (na | p) << 1) # 设置标记并移位
n = 8
count = 0
DFS(0, 0, 0, 0)
print(count)
这篇关于位运算解决八皇后的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!