In [4]: n = 8
In [5]: x =[]
In [6]: X = [] #所有解
In [8]: def conflict(k): #冲突检测
...: global x
...: for i in range(k):
...: if x[i]==x[k] or abs(i-k) ==abs(x[i]-x[k]):
...: return True
...: return False
...:
In [9]: def queens(k):
...: global n,x,X
...: if k>=n:
...: X.append(x[:])#加入一个解
...: else:
...: for i in range(n):
...: x.append(i)
...: if not conflict(k):
...: queens(k+1)#成功则继续搜索下一列
...: x.pop()#失败回溯,换一列
...:
...:
In [10]: def show(x):
...: global n
...: for i in range(n):
...: print('. '*(x[i])+'X '+'. '*(n-x[i]-1))
In [11]: print(X[-1])
[7, 3, 0, 2, 5, 1, 6, 4]
In [12]: show(X[-1])
. . . . . . . X
. . . X . . . .
X . . . . . . .
. . X . . . . .
. . . . . X . .
. X . . . . . .
. . . . . . X .
. . . . X . . .