## 初始化棋盘矩阵和用来表示约束条件的矩阵
def initial(p,limit):
for i in range(0,8):
p[i] = list(range(8))
limit[i] = list(range(8))
for x in range(8):
for y in range(8):
p[x][y] = 0
limit[x][y] = 1
return p,limit
def getPL():
p = list(range(8))
limit = list(range(8))
initial(p,limit)
return p,limit
# 增加约束条件
def addLimit(limit,x,y):
limit[x][y] = 0
for i in range(8):
limit[x][i] = 0
for i in range(8):
limit[i][y] = 0
tx,ty = x+1,y+1
while tx <8 and ty <8:
limit[tx][ty] = 0
tx += 1
ty += 1
tx,ty = x-1,y-1
while tx >=0 and ty >=0 :
limit[tx][ty] = 0
tx -= 1
ty -= 1
tx,ty = x+1,y-1
while tx in range(8) and ty in range(8):
limit[tx][ty] = 0
tx += 1
ty -= 1
tx,ty = x-1,y+1
while tx in range(8) and ty in range(8):
limit[tx][ty] = 0
tx -= 1
ty += 1
## 获得可以放入的位置
def get_potential_position_list(limit):
re = []
for x in range(8):
for y in range(8):
if limit[x][y] :
re.append((x,y))
return re
# no potential positon
## 复制
def copy(p,l):
p_,l_ = getPL()
for i in range(len(p)):
for j in range(len(l)):
p_[i][j] = p[i][j]
l_[i][j] = l[i][j]
return p_,l_
## 放入queen 返回新的棋盘 和 表示约束的矩阵
def insert_no_sf(p,x,y,limit):
pc,lc= copy(p,limit)
insert(pc,x,y,lc)
return pc,lc
## 放入queen
def insert(p,x,y,limit):
p[x][y] = 1
addLimit(limit,x,y)
## 深度优先搜索
def search_wrapper(p,l):
p_in = p
l_in = l
##用来判断 base case
done = False
def search(p,l):
nonlocal done
nonlocal p_in
if done:
return
c = count(p)
if c == 8 :
done = True
p_in = p
return
else:
## 递归访问树
pot = get_potential_position_list(l)
## 出现冲突则停止递归
if len(pot)+c <8 :return
for x,y in pot:
p_,l_ = insert_no_sf(p,x,y,l)
search(p_,l_)
search(p_in,l_in)
return p_in
# queens count
def count(p):
count__ = 0
for x in p:
for y in x:
if y:
count__ += 1
return count__
p,l = getPL()