python解决八皇后问题

运用python的生成器可轻松解决八皇后问题

使用元组表示可能的解,其中每个元素表示相应行中皇后所在位置(列),即state[0]=3,则说明第一行的皇后在第4列。

# _*_ coding:utf-8 _*_
import random

#检测冲突
def conflict(state, nextX):         #state为各皇后相应位置
    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=()):        #num为皇后数
    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))
        
print(list(queens(4)))            #list()输出全部排序结果
print()
prettyprint(random.choice(list(queens(8))))  

成果展示:
link

猜你喜欢

转载自www.cnblogs.com/junecode/p/11829692.html