思路:
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..