python生成器解决八皇后


首先我们写一个conflict函数来判断下一个皇后的位置是否和前面的皇后的放置位置产生冲突.

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(8):
        if not conflict(state, pos):
            if len(state) == num - 1:
                yield (pos,)
            else:
                for result in queens(num, state + (pos,)):
                    yield (pos,) + result

主程序

if __name__== '__main__':
    result = list(queens(8))
    print(result)
    num = len(result)
    print(num)

结果:
[(0, 4, 7, 5, 2, 6, 1, 3), (0, 5, 7, 2, 6, 3, 1, 4), (0, 6, 3, 5, 7, 1, 4, 2), (0, 6, 4, 7, 1, 3, 5, 2)...]
92

你可能感兴趣的:(python生成器解决八皇后)