標籤:添加 print turn return 座標 ret length abs code
1 import random 2 #衝突檢查,在定義state時,採用state來標誌每個皇后的位置,其中索引用來表示橫座標,基對應的值表示縱座標,例如: state[0]=3,表示該皇后位於第1行的第4列上 3 def conflict(state, nextX): 4 nextY = len(state) 5 for i in range(nextY): 6 #如果下一個皇后的位置與當前的皇后位置相鄰(包括上下,左右)或在同一對角線上,則說明有衝突,需要重新擺放 7 if abs(state[i]-nextX) in (0, nextY-i): 8 return True 9 return False10 11 #採用產生器的方式來產生每一個皇后的位置,並用遞迴來實現下一個皇后的位置。12 def queens(num, state=()):13 for pos in range(num):14 if not conflict(state, pos):15 #產生當前皇后的位置資訊16 if len(state) == num-1:17 yield (pos, )18 #否則,把當前皇后的位置資訊,添加到狀態列表裡,並傳遞給下一皇后。19 else:20 for result in queens(num, state+(pos,)):21 yield (pos, ) + result22 23 24 #為了直觀表現棋盤,用X表示每個皇后的位置25 def prettyprint(solution):26 def line(pos, length=len(solution)):27 return ‘. ‘ * (pos) + ‘X ‘ + ‘. ‘*(length-pos-1)28 for pos in solution:29 print line(pos)30 31 if __name__ == "__main__":32 prettyprint(random.choice(list(queens(8))))
python學習八皇后問題