求解八皇后问题的Python代码
#to check if the queen is at the valid place
def check_pos(loop, value):
for index in range(loop):
data = EQ[index]
if value == data:
return False
if (index + data) == (loop + value):
return False
if (index - data) == (loop - value):
return False
return True
#to place the queen
def eight_queen(index):
for loop in range(8):
if(check_pos(index, loop) == True):
EQ[index] = loop
if(index == 7):
print(EQ)
EQ[index] = 0;
return
eight_queen(index + 1)
EQ[index] = 0
EQ = list(range(8))
eight_queen(0)
本文提供了一种解决八皇后问题的有效Python实现方法。通过递归回溯算法确定每个皇后的位置,确保没有两个皇后处于同一行、列或对角线上。代码详细展示了如何检查每个位置的有效性,并最终输出所有可行的解决方案。
621

被折叠的 条评论
为什么被折叠?



