Using python generators can easily solve the eight queens problem
Tuple indicates possible solutions, where each element represents a position where corresponding row Queen (column), i.e., state [0] = 3, then the first row Queen in column 4.
# _*_ coding:utf-8 _*_
import random
#检测冲突
def conflict(state, nextX): #state为各皇后相应位置
nextY = len(state)
for i in range(nextY):
if abs(state[i] - nextX) in (0, nextY - i): #下一个皇后与当前皇后在同一列或位于同一对角线
return True
return False
#递归
def queens(num=8, state=()): #num为皇后数
for pos in range(num):
if not conflict(state, pos):
if len(state) == num - 1:
yield (pos,)
else:
for result in queens(num, state + (pos,)):
yield (pos,) + result
#图形输出(随机一结果)
def prettyprint(solution):
def line(pos, length=len(solution)): #辅助函数
return '. ' * (pos) + 'X ' + '. ' * (length-pos-1)
for pos in solution:
print(line(pos))
print(list(queens(4))) #list()输出全部排序结果
print()
prettyprint(random.choice(list(queens(8))))
The results show: