Python solve the eight queens problem

Questions introduced

Eight queens problem is to chess as a background question: How can \ (8 \ times8 \) to place eight queens on a chess board, so that the queen can not eat any other directly Queen? For this purpose, any two Queens are not the same in the transverse, longitudinal or diagonal lines. Eight Queens problem can be extended to a more general problem of placing n queens.

To solve n queens problem, first of all into a new queens on a chessboard, and this position will not be eaten previously placed the Queen, the Queen of the new location onto the stack. However, if you place the new Queen of the row (or column) of the eight positions have no way to place the new Queen (placed in any position, will be placed before the old Queen to eat), then it must be from the stack a pop-up position before the queen, and again looking for another new location in the row (or column) to put in, then this position is pushed onto the stack, and in this way a kind of backtracking (backtracking) algorithm application .

img

The sample code

Codes from the References [2].

global queen
global number
EIGHT=8 #定义堆栈的最大容量
queen=[None]*8 #存放8个皇后的行位置

number=0    #计算总共有几组解的总数
#决定皇后存放的位置
#输出所需要的结果
def print_table():
    global number
    x=y=0
    number+=1
    print('')
    print('八皇后问题的第%d组解\t' %number)
    for x in range(EIGHT):
        for y in range(EIGHT):
            if x==queen[y]:
                print('<q>',end='')
            else:
                print('<->',end='')
        print('\t')
    input('\n..按下任意键继续..\n')

#测试在(row,col)上的皇后是否遭受攻击
#若遭受攻击则返回值为1,否则返回0
def attack(row,col):
    global queen
    i=0
    atk=0
    offset_row=offset_col=0
    while (atk!=1)and i<col:
        offset_col=abs(i-col)
        offset_row=abs(queen[i]-row)
        #判断两皇后是否在同一行或在同一对角线上
        if queen[i]==row or offset_row==offset_col:
            atk=1
        i=i+1
    return atk

def decide_position(value):
    global queen
    i=0
    while i<EIGHT:
        if attack(i,value)!=1:
            queen[value]=i
            if value==7:
                print_table()
            else:
                decide_position(value+1)
        i=i+1

#主程序
decide_position(0)

Run results are shown below:

1563199003968

【References】

[1] Baidu Encyclopedia: Eight Queens problem

[2] Wu Canming illustrates data structures: Use Python [M] Beijing: Tsinghua University Press, 2018

Guess you like

Origin www.cnblogs.com/IvyWong/p/11814248.html