八皇后问题-recall算法
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numbers
import numpy
import math
'''
八皇后为题:
在国际象棋棋盘上摆放八个皇后,相互之间不能相互冲突
-----------------------------------------
第i个Q(位置:x=i,y=j)皇后(i,0)开始,
1若有其他皇后位置与之冲突(y(i)==y(i-1)或者|x(i)-x(i-1)|=|y(j)-y(j-1)|)
2则将j+1,继续第一步
3若j=7时仍不能找到合适位置,则第i-1个皇后继续向前移动
3若能找到避免冲突则i+1,4重复1
0<=i<=7
0<=j<=7
'''
postion=[]
def recall(pos):
lastx = len(pos)
conflict=0
if lastx==8:
print(pos)
#return True
for lasty in range(0,8):
conflict = 0
if lastx==0:
pos.append(lasty)
if recall(pos):
pass
else:
del pos[-1]
else:
for i in range(0,lastx):
if lasty==pos[i] or abs(lastx-i)==abs(lasty-pos[i]):
conflict=1
if conflict==0:
pos.append(lasty)
if recall(pos):
pass
else:
del pos[-1]
return False
recall(postion)
[0, 4, 7, 5, 2, 6, 1, 3]
[0, 5, 7, 2, 6, 3, 1, 4]
[0, 6, 3, 5, 7, 1, 4, 2]
[0, 6, 4, 7, 1, 3, 5, 2]
[1, 3, 5, 7, 2, 0, 6, 4]
[1, 4, 6, 0, 2, 7, 5, 3]
[1, 4, 6, 3, 0, 7, 5, 2]
[1, 5, 0, 6, 3, 7, 2, 4]
[1, 5, 7, 2, 0, 3, 6, 4]
[1, 6, 2, 5, 7, 4, 0, 3]
[1, 6, 4, 7, 0, 3, 5, 2]
[1, 7, 5, 0, 2, 4, 6, 3]
[2, 0, 6, 4, 7, 1, 3, 5]
[2, 4, 1, 7, 0, 6, 3, 5]
[2, 4, 1, 7, 5, 3, 6, 0]
[2, 4, 6, 0, 3, 1, 7, 5]
[2, 4, 7, 3, 0, 6, 1, 5]
[2, 5, 1, 4, 7, 0, 6, 3]
[2, 5, 1, 6, 0, 3, 7, 4]
[2, 5, 1, 6, 4, 0, 7, 3]
[2, 5, 3, 0, 7, 4, 6, 1]
[2, 5, 3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