八皇后问题--

八皇后问题

问题描述:

将八个皇后放入8*8的棋盘,任何皇后都不能吃掉其它皇后

# 冲突检测函数
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,state):
    if len(state) == num-1:
        for pos in range(num):
            if not conflict(state,pos):
                yield pos

s=list(queens(4,(1,3,0)))
print(s)
'''

# 
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


#输出所有结果
s=list(queens(8))
print('解个数:',len(s))
# 输出所有结果
for res in s:
    print(res)

你可能感兴趣的:(python)