Data Structure and Algorithm_Recursion_Eight Queen

Problem Description

Introduction to the
Eight Queens Problem The Eight Queens problem is an ancient and well-known problem, which is a typical case of the backtracking algorithm. The problem was raised by international chess player Max Bethel in 1848: placing eight queens on an 8 × 8 grid chess to prevent them from attacking each other, that is, any two queens cannot be on the same line , In the same column or on the same slash, ask how many pendulums there are.
Insert picture description here

Mental analysis

Because chess is an 8 * 8 board, and a total of 8 queens need to be placed on the board. Then there must be only one queen in each row, then you can directly use a one-dimensional array, using its subscript to represent the number of rows, and the value of the array represents the number of columns corresponding to each row.
The specific steps are as follows:
1) The first queen is placed in the first column of the first row
2) The second queen is placed in the first column of the second row, and then judge whether it is OK; if it is not OK, then move horizontally to the right until Find a suitable position
3) Continue to the third queen, or repeat the operation of the second line, and at the same time determine whether there is a conflict with the first line and the second line until you find a suitable position
4) When you get a correct solution, in When the stack rolls back to the previous stack, it will start backtracking, that is, put all the solutions of the first queen into the first row, all get
5) and then put the first queen into the second column, and then execute 1 in the loop. 2, 3, 4 steps

Specific code:

import math

class Queue(object):
    

    def __init__(self):
        self.cnt = 0#统计八个皇后的满足要求的摆放方式的个数
        self.maxn = 8#数组的最大长度
        self.array = [0 for i in range(8)]#数组下标代表行,每个下标的值为列

    '''
    打印皇后位置数组
    '''
    def Print(self):
        for i in range(len(self.array)):
            print("%d "%self.array[i],end='')
        print()
    '''
    判断当前皇后位置和前几个皇后的位置是否冲突
    '''
    def judge(self,n):
        for i in range(n):
            if self.array[i]==self.array[n] or abs(n-i)==abs(self.array[n]-self.array[i]):
                return False
        return True
    '''
    回溯递归
    '''
    def check(self,n):
        if n==self.maxn:
            self.cnt+=1
            self.Print()
            return
        for i in range(self.maxn):
            self.array[n]=i
            if self.judge(n):
                self.check(n+1)

q = Queue()
q.check(0)
num = q.cnt
print('总共:%d'%num)

Published 27 original articles · praised 2 · visits 680

Guess you like

Origin blog.csdn.net/qq_44273739/article/details/105173462