# 回溯法解决八皇后问题
def place(l, k):
for i in range(1,k):
if l[i] == l[k] or abs(k-i) == abs(l[k]-l[i]):
return False
return True
# 循环
def queue(n):
l = [0]*(n+1)
k = 1
while k >= 1:
l[k] += 1
while l[k] <= n and not place(l, k):
l[k] += 1
if l[k] <= n and k == n:
print '-'*10
for i in l:
print i, " ",
print
# 进入下一个放置点
elif l[k] <= n and k < n:
k += 1
# 回溯
else:
l[k] = 0
k -= 1
# 递归
def queue2(n,k,l):
if k == n+1:
print '-' * 20
for i in l:
print i, " ",
print
else:
for i in range(1,n+1):
l[k] = i
if place(l,k)and k<=8:
queue2(n,k+1,l)