python基础教程第二版的八皇后,自己学习的笔记记录下来

来源:互联网 发布:乳胶床垫 儿童 知乎 编辑:程序博客网 时间:2024/05/22 07:48
  # 八皇后的算法学习




# nextX,nextY代表下一个皇后的位置
# 函数对前面的每一个皇后位置进行检查,如果下一个皇后和前面的皇后有相同水平位置或者是同一个对角线就True,否则为False


# 定义一个检查冲突的函数
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




# 如果只剩一个皇后没有位置,那么遍历它所有的可能,返回没有冲突的位置,num参数是皇后总数,state参数是存放前面皇后的位置信息的元组
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




# 打包
def prettyPrint(solution):
    def line(pos, length=len(solution)):
        return '. ' * (pos) + 'X ' + '. ' * (length - pos - 1)


    for pos in solution:
        print (line(pos))




import random
prettyPrint(random.choice(list(queens(8))))
0 0