八皇后算法

from itertools import permutations
class Queen():
    def __init__(self,num=8):
        self.num = num
    def putQueen(self):
        xylist=[]
        for group in permutations(range(self.num)):
            xylist.append([(group[i],i) for i in range(self.num)])
        for xygroup in xylist:
            if len(set((xy[0]+xy[1] for xy in xygroup)))==len(set((xy[0]-xy[1] for xy in xygroup)))==self.num:
                yield xygroup
print len(list(Queen().putQueen()))

from itertools import permutations
class Queen():
    def __init__(self,num=8):
        self.num = num
    def putQueen(self):
        for group in permutations(range(self.num)):
            if (self.num == len(set(group[i]+i for i in range(self.num)))== len(set(group[i]-i for i in range(self.num)))):
                yield [(group[i],i) for i in range(self.num)]
print len(list(Queen().putQueen()))  

from itertools import permutations
class Queen():
    def __init__(self,num=8):
        self.num = num
    def putQueen(self):
        for group in permutations(range(self.num)):
            if self.conditions(group):
                yield [(group[i],i) for i in range(self.num)]
    def conditions(self,group):
        for n in range(self.num):
            for m in range(n):
                if abs(group[n]-group[m]) in (0,n-m):
                    return False
        return True
print len(list(Queen().putQueen()))

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 conflict(state,nextX):
    nextY = len(state)
    for i in range(nextY):
        if abs(state[i]-nextX) in (0,nextY-i):
            return True
    return False
print len(list(queens()))

from itertools import permutations
n = 8
cols = range(n)
for vec in permutations(cols):
    if (n == len(set(vec[i]+i for i in cols))== len(set(vec[i]-i for i in cols))):
        print vec
    原文作者:八皇后问题
    原文地址: https://blog.csdn.net/zlymhh/article/details/9617849
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞