八皇后問題(參考《Python基礎教程》)


思路:

1. 使用元組或者列表記錄位置

2. 定義函數conflict(state, nextX),沖突返回True,不沖突返回False

3. 定義遞歸函數queens(num, state)

若是最后一行 對於 x in range(num)調用conflict(state, num) ,如果沒有沖突,返回x

若不是最后一行 對於x in range(num)調用conflict(state, num), 如果沒有沖突,state更新,遞歸調用queens(num, state)

4. 每一種可能的情況使用生成器進行了保存(yield使用方法參加前一篇:生成器編程實踐)

元組實現

 1 def conflict(state, nextX):
 2     nextY = len(state)
 3     for i in range(nextY):
 4         if abs(nextX-state[i]) in (0, nextY-i):
 5             return True
 6     return False
 7 
 8 def queens(side_length, state=()):
 9     for pos in range(side_length):
10         if not conflict(state, pos):
11              if len(state) == side_length-1:
12                 yield (pos,)
13              else:
14                 for result in queens(side_length, state+(pos,)):
15                     yield (pos,)+result
16 
17 def prettyprint(solution):
18     def line(pos, length = len(solution)):
19         return '.'*(pos) + 'X' + '.'*(length-pos-1)
20     for pos in solution:
21         print line(pos)
22 
23 
24 for solution in list(queens(4)):
25     prettyprint(solution)

Output

1 .X..
2 ...X
3 X...
4 ..X.
5 ..X.
6 X...
7 ...X
8 .X..

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM