# 使用回溯法解决N皇后的问题
def mk_lst(size): # 生成棋盘
return [[0 for i in range(size)] for j in range(size)]
def is_legal_posi(loca, size): # 判断是否合法坐标
x, y = loca[0], loca[1]
size -= 1
if 0 <= x <= size and 0 <= y <= size:
return True
else:
return False
def place(loca, size, num, lst): # 放置皇后棋子,num设置1 表示放置皇后,0表示拿走皇后
lst = lst[:]
x, y = loca[0], loca[1]
r = range(-size, size + 1)
row = [(_, y) for _ in r if is_legal_posi((_, y), size)]
col = [(x, _) for _ in r if is_legal_posi((x, _), size)]
up = [(x + _, y + _) for _ in r if is_legal_posi((x + _, y + _), size)]
down = [(x - _, y + _) for _ in r if is_legal_posi((x - _, y + _), size)]
for i in row, col, up, down:
for j in i:
lst[j[0]][j[1]] = num
def add_next(loca, size, lst): # 如果到最后一行, 或者下一行没有位置 就返回False
x, y = loca[0], loca[1]
if x + 1 > size - 1: # 说明到底了
return False
l = [(x + 1, _) for _ in range(size) if lst[x + 1][_] != 1]
if not l:
return False
else:
return l
def solution(size):
path, count_l, outcome, final = [], [], [], []
for loca in [(0, i) for i in range(size)]: # 初始位置
path.append(loca)
count_l.append(len(path))
while path:
lst = mk_lst(size)
outcome.append(path.pop())
count_l[-1] -= 1
for loca in outcome:
place(loca, size, 1, lst)
l = add_next(loca, size, lst)
if l:
count_l.append(len(l))
for i in l:
path.append(i)
else:
if len(outcome) == size:
final.append(outcome[:])
if outcome:
outcome.pop()
t = 0
while count_l:
if count_l[-1] == 0:
count_l.pop()
t += 1
else:
break
if t:
for i in range(t):
if outcome:
outcome.pop()
print(len(final))
return final
solution(8)
回溯法解决N皇后的问题
猜你喜欢
转载自blog.csdn.net/qq_32835305/article/details/86560657
今日推荐
周排行