八皇后问题 python

Sum = 0

a = [0 for i in range(100)]
b = [0 for i in range(100)]
c = [0 for i in range(100)]
d = [0 for i in range(100)]

def Print():
    global Sum
    Sum += 1
    print("Sum = "+str(Sum))
    for i in range(1,9):
        print("{: <4}".format(a[i]),end=' ')
    print()

def search(i):
    for j in range(1,9):
        if b[j]==0 and c[i+j]==0 and d[i-j+7]==0:
            a[i] = j
            b[j] = 1
            c[i+j] = 1
            d[i-j+7] = 1
            if i == 8:
                Print()
            else:
                search(i+1)
            b[j] = 0
            c[i+j] = 0
            d[i-j+7] = 0


search(1)

你可能感兴趣的:(竞赛)