回溯法:《8皇后问题》-python实现

该问题是国际西洋棋棋手马克斯·贝瑟尔于1848年提出:在8×8格的国际象棋上摆放八个皇后,使其不能互相攻击,即任意两个皇后都不能处于同一行、同一列或同一斜线上,问有多少种摆法。

 

思路:一行一行的放置皇后,判断皇后的位置是否符合条件,当放置到最后一行时,则所有皇后的位置放置完毕,保存棋盘活棋盘数加一。

 

#coding:utf-8
import copy
c = 0

def notdanger(b, row, x, y):                #判断皇后的放置位置(x,y)是否满足每一行、每一列,斜线都只有(x,y)一个皇后
    t1 = True
    t2 = True
    t3 = True
    t4 = True
    t5 = True

    for iii in range(0, row):
        if b[iii][y] == 1:
            t1 = False
            break

    iii = x
    jjj = y
    while iii >= 0 and jjj >= 0:
        if b[iii][jjj] == 1:
            t2 = False
            break
        iii = iii - 1
        jjj = jjj - 1

    iii = x
    jjj = y
    while iii >= 0 and jjj < row:
        if b[iii][jjj] == 1:
            t3 = False
            break
        iii = iii - 1
        jjj = jjj + 1

    iii = x
    jjj = y
    while iii < row and jjj >= 0:
        if b[iii][jjj] == 1:
            t4 = False
            break
        iii = iii + 1
        jjj = jjj - 1

    iii = x
    jjj = y
    while iii < row and jjj < row:
        if b[iii][jjj] == 1:
            t5 = False
            break
        iii = iii + 1
        jjj = jjj + 1

    return t1 and t2 and t3 and t4 and t5


def eightqueen(a, row, i):
    b = copy.deepcopy(a)
    if i == 8:                                   #一行一行的放置皇后,当放置到第8行时,结果满足条件,棋盘数+1
        global c
        c = c + 1
        print c
    else:
        for ii in range(0, 8):
            if notdanger(b, row, i, ii):        #判断棋盘的(i, ii)位置是否符合要求
                for jj in range(0, row):
                    b[i][jj] = 0
                b[i][ii] = 1                    #符合要求,将皇后放置在该位置
                eightqueen(b, row, i + 1)


if __name__ == '__main__':
    a = []
    for i in range(0, 8):
        b = []
        for j in range(0, 8):
            b.append(0)
        a.append(b)

    eightqueen(a, 8, 0)                 #a表示初始棋盘,8表示棋盘的行列数,0表示棋盘的第几行

    #print c

 

    原文作者:回溯法
    原文地址: https://blog.csdn.net/w113691/article/details/81558534
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞