八皇后问题 Python 代码实现与解析
八皇后问题是一个经典的回溯算法问题,其目标是在一个 8x8 的棋盘上放置 8 个皇后,使得任意两个皇后都不在同一行、同一列或同一对角线上。以下是 Python 代码实现:
def conflict(state, nextX):
nextY = len(state)
for i in range(nextY):
if abs(state[i] - nextX) in (0, nextY - i):
return True
return False
def queens(num=8, state=()):
for pos in range(num):
if not conflict(state, pos):
if len(state) == num - 1:
yield (pos, )
else:
for result in queens(num, state + (pos, )):
yield (pos, ) + result
其中,conflict 函数用于判断当前位置是否和之前的皇后冲突,queens 函数则是递归地尝试每一个位置。使用时,可以通过以下方式获取所有可能的解:
print(list(queens()))
原文地址: https://www.cveoy.top/t/topic/l3qc 著作权归作者所有。请勿转载和采集!