import random def judge(state, nextX): #判断是否和之前的皇后状态有冲突
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 = ()):
for pos in range(num):
if not judge(state, pos):
if len(state) == num-1:
yield (pos,) #(pos,)中的逗号使其必须被设置为元组而不是简单地加上括号
else:
for result in queens(num, state+(pos,)):
yield (pos,)+result def randomPrint(solution):
for i in range(8):
print( '•'*solution[i]+'X'+'•'*(8-solution[i]-1)) ans = int(len(list(queens(8))))
print(ans)
randomPrint(random.choice(list(queens()))) #随机输出一种情况