1 import random 2 3 def judge(state, nextX): #判断是否和之前的皇后状态有冲突 4 nextY = len(state) 5 for i in range(nextY): 6 if abs(state[i]-nextX) in (0,nextY-i): 7 return True 8 return False 9 10 def queens(num = 8, state = ()): 11 for pos in range(num): 12 if not judge(state, pos): 13 if len(state) == num-1: 14 yield (pos,) #(pos,)中的逗号使其必须被设置为元组而不是简单地加上括号 15 else: 16 for result in queens(num, state+(pos,)): 17 yield (pos,)+result 18 19 def randomPrint(solution): 20 for i in range(8): 21 print( '•'*solution[i]+'X'+'•'*(8-solution[i]-1)) 22 23 ans = int(len(list(queens(8)))) 24 print(ans) 25 randomPrint(random.choice(list(queens()))) #随机输出一种情况