Eight queens problem of classical algorithm

Time:2020-1-16

The eight queens problem is an old and famous problem, which is a classic case of learning backtracking algorithm. Let’s explore it together today!

Eight queens problem of classical algorithm

Back in 1848, international chess player Max Bethel raised such a question,

Put eight queens on the 8 × 8 grid chess, so that they can’t attack each other, that is, any two Queens can’t be in the same row, the same column or the same diagonal line, and ask how many kinds of placement there are in total.

Later, different scholars put forward their own opinions. Gauss, a great mathematician, thinks there are 76 kinds of pendulum methods. In 1854, different authors published 40 different opinions in Berlin chess magazine. Later, some people got 92 kinds of pendulum methods by using graph theory.

Now, through our computer and programming language, we can easily solve this problem.

The most direct and easy to think of solution is the violence method. We can choose eight queens in the 8 × 8 lattice. After selection, we can see whether any two queens are not in the same row and the same slash. If they are satisfied, we can cumulatively meet the conditions. After studying permutation and combination, we found that the number of 8 out of 64 reached 4 billion, which is obviously unacceptable.

Eight queens problem of classical algorithm
But according to this condition, we can make some artificial choices. For example, according to the condition, we know that each row and column can only have one queen at most, which can reduce the scale of the problem to a certain extent. In the first row, if you choose to place a queen in one column, there are eight different choices. In the second row, you can only choose the remaining seven columns, that is, seven choices. The choices of each remaining row will decrease by 1. Then there are eight factorials in the total options available, which is far better than the solution of violence. But the time complexity of this factorial is probably unacceptable, Is there a better solution?

Eight queens problem of classical algorithm

That’s natural, and that’s the recursive backtracking method.

When we choose the position of the first queen, we can’t choose the position on the same slant line as the position in the same row. The second queen can only be placed on the position that is not radiated by the first queen, and then the third queen can’t be placed on the position that is radiated by the first two queens. If there is no position that is not radiated at this time, it will be It means that this method is not feasible. We need to go back to the previous step, choose a new position for the second queen that has not been radiated by the first queen, and then see whether there is a position for the third queen to put. If there is still no position, then go back to choose the second queen. If there is no more choice for the second queen, then go back to the first queen, and then go back Select the location.

Eight queens problem of classical algorithm

The overall method is as described above. Next, we use intuitive code to implement this algorithm,

def find_Queen(row):

    if row>7:
        global count
        count+=1
        print_queen()
        return
    
    for column in range(8):
        if check(row,column):
            Queen[row][column]=1
            find_Queen(row+1)
            Queen[row][column]=0

Define a two-dimensional array queen. If the corresponding position in the array is 1, it means that the queen is placed in this position, and the position of the queen is placed by lines. If the current selection cannot continue to find the position of the queen, reset it to 0 with 1 in front, that is to sayRegression。 The main purpose of check function is to filter the proper position of Queen to meet the conditions. It can be divided into three parts: row and column inspection, main diagonal and negative diagonal inspection.

def check(row,column):
    
    #Check row and column
    for k in range(8):
        if Queen[k][column]==1:
            return False
        
    #Check the main diagonal    
    
    for i,j in zip(range(row-1,-1,-1),range(column-1,-1,-1)):
        if Queen[i][j]==1:
            return False   
        
    #Check the secondary diagonal     
    for i,j in zip(range(row-1,-1,-1),range(column+1,8)):
        if Queen[i][j]==1:
            return False          

    return True

When eight queens have been placed, enter the if statement, accumulate the values and print out the corresponding schematic diagram of Queen placement.

Eight queens problem of classical algorithm

The star of the entity indicates that the queen is placed in the current position, and the specific print code is as follows,

def print_queen():
    
    print(Queen)
    for i in range(8):
        for j in range(8):
            if Queen[i][j]==1:
                print('☆ '*j+'★ '+'☆ '*(7-j))
    print("\n\n")

In this way, we find 92 solutions of the eight queens by recursive backtracking, and print them out in a formal way. Through the study of the eight queens problem, we can deeply experience the thought of backtracking~

Recommended Today

Ios15 adaptation

Need immediate modification 1. Uinavigationbar, uitoolbar and uitabbar styles Uinavigationbar, uitoolbar and uitabbar need to use uibarappearance APIs to set colors. // UINavigationBar let navigationBarAppearance = UINavigationBarAppearance() navigationBarAppearance.backgroundColor = .red navigationController?.navigationBar.scrollEdgeAppearance = navigationBarAppearance navigationController?.navigationBar.standardAppearance = navigationBarAppearance // UIToolbar let toolBarAppearance = UIToolbarAppearance() toolBarAppearance.backgroundColor = .blue navigationController?.toolbar.scrollEdgeAppearance = toolBarAppearance navigationController?.toolbar.standardAppearance = toolBarAppearance // UITabBar let tabBarAppearance […]