位运算解决八皇后

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)
上一篇:学习记录: httpie


下一篇:谷歌正式发布 Android 9,代号为 Pie