python八皇後
Ⅰ python關於八皇後判斷沖突函數的一些邏輯小問題
代碼確實不對false的返回位置不對,另外你的問題答案是在一條對角線說明兩點連接的斜率為1或負1,也就是橫坐標相減的絕對值等於縱坐標相減
Ⅱ python解決八皇後演算法
global col #定義一些全局變數
global row
global pos_diag
global nag_diag
global count
def output():
''' 輸出一種有效結果
'''
global count
print row
count += 1
def do_queen(i):
''' 生成所有正確解
@param i: 皇後的數目
'''
for j in range(0, 8): #依次嘗試0~7位置
if col[j] == 1 and pos_diag[i-j+7] == 1 and nag_diag[i+j] == 1: #若該行,正對角線,負對角線上都沒有皇後,則放入i皇後
row[i] = j
col[j] = 0 #調整各個列表狀態
pos_diag[i-j+7] = 0
nag_diag[i+j] = 0
if i < 7:
do_queen(i+1) #可遞增或遞減
else:
output() #產生一個結果,輸出
col[j] = 1 #恢復各個列表狀態為之前的
pos_diag[i-j+7] = 1
nag_diag[i+j] = 1
if __name__ == '__main__':
col = [] #矩陣列的列表,存儲皇後所在列,若該列沒有皇後,則相應置為1,反之則0
row = [] #矩陣行的列表,存放每行皇後所在的列位置,隨著程序的執行,在不斷的變化中,之間輸出結果
pos_diag = [] #正對角線,i-j恆定,-7~0~7,並且b(i)+7統一到0~14
nag_diag = [] #負對角線,i+j恆定,0~14
count = 0
for index in range(0, 8): #一些初始化工作
col.append(1)
row.append(0)
for index in range(0, 15):
pos_diag.append(1)
nag_diag.append(1)
do_queen(0) #開始遞歸,先放一個,依次遞增,反過來,從7開始遞減也可
print 'Totally have %d solutions!' % count
輸出:
[0, 4, 7, 5, 2, 6, 1, 3]
[0, 5, 7, 2, 6, 3, 1, 4]
[0, 6, 3, 5, 7, 1, 4, 2]
[0, 6, 4, 7, 1, 3, 5, 2]
[1, 3, 5, 7, 2, 0, 6, 4]
[1, 4, 6, 0, 2, 7, 5, 3]
[1, 4, 6, 3, 0, 7, 5, 2]
[1, 5, 0, 6, 3, 7, 2, 4]
[1, 5, 7, 2, 0, 3, 6, 4]
[1, 6, 2, 5,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2, 5, 1, 6, 4]
Totally have 92 solutions!
Ⅲ 求高手解八皇後問題(python)
pos是從0到num-1走的
pos=0時程序走這一段:
for result in queens(num, state + (pos,)):
yield (pos,) + result
就是先找第一個位置
Ⅳ python中if __name__ == "__main__":的求問,這句話是true嗎,為什麼,代碼如圖,是八皇後問題代碼
__name__ == "__main__"
__name__ 是模塊的一個屬性,如果模塊是被執行的話, 那麼值為__main__,如果被導入的話那麼就是模塊名