python學習八皇后問題

來源:互聯網
上載者:User

標籤:添加   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學習八皇后問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.