0
点赞
收藏
分享

微信扫一扫

回顾一下8皇后

西风白羽 2022-03-19 阅读 45
python

直接贴结果好了,闲来无事写的

chessMap = list()
waitMap = list()
checkMap = list()
bigMap = list()

def testChess(chessMap: list, x, y):
    '''检查放下后有无干涉'''
    for chess in chessMap:
        # 对已经放下的棋子,检查能否放置下一个
        if chess[0] == x or chess[1] == y or chess[0] - chess[1] == x - y or chess[0] + chess[1] == x + y:
            return chess
    return [x, y]


def findlast():
    global waitMap
    global checkMap
    ret = dict()
    ret['end'] = 0
    i = 0
    while i < len(checkMap):
        if checkMap[i] == 0:
            ret['data'] = waitMap[i]
            ret['i'] = i
            ret['x'] = ret['data'][-1][0]
            ret['end'] = 1
            return ret
        i += 1
    return ret

n = 8
x = 0
while x < n:
    y = 0
    y2 = 0
    firstFlag = -1
    while y2 < n:
        hisMap = chessMap.copy()
        ret = testChess(chessMap, x, y2)
        if ret[0] == x and ret[1] == y2:
            hisMap.append(ret)
            waitMap.append(hisMap)
            if firstFlag < 0:
                # 找到下一行第一个时
                firstFlag = len(hisMap) - 1
                checkMap.append(1)
                y = y2
            else:
                checkMap.append(0)
        y2 += 1

    if firstFlag == -1:
        x = n
    else:
        chessMap.append([x, y])
    x += 1

    if x >= n:
        if len(chessMap) == n:
            # 完成所有已知搜索
            bigMap.append(chessMap)

        # 最近的可选项再次搜索
        last = findlast()
        if last['end']==1:
            chessMap = last['data'].copy()
            checkMap[last['i']] = 1
            x = last['x'] + 1
        else:
            print('搜索结束,共计%s种结果' % (len(bigMap)))
            pass
pass
举报

相关推荐

0 条评论