Recursion--Eight Queens Problem (combined with Java code explanation)

Eight queens problem statement

The eight queens problem is an old and well-known problem, and it is a typical case of backtracking algorithms. The problem was raised by international chess player Max Bethel in 1848: Place eight queens on an 8×8 grid chess so that they cannot attack each other, that is: any two queens cannot be in the same row , on the same column or on the same oblique line, ask how many pendulum methods there are.

insert image description here

Analysis of Eight Queens

(Refer to Han Shunping's analysis of the eight queens' thinking on station B)

  1. The first queen is first placed in the first row and first column.
  2. Put the second queen in the first column of the second row, and then judge whether it is OK. If not, continue to put it in the second column and the third column, and put all the columns in turn to find a suitable position.
  3. Continue to the third queen, or the first column, the second column... until the 8th queen can also be placed in a non-conflicting position, it is considered to have found a correct solution.
  4. When a correct solution is obtained, when the stack rolls back to the previous stack, it will start backtracking, that is, all the correct solutions that are placed in the first column of the first queen will be obtained.
  5. Then go back and continue to put the first queen in the second column, and then continue to perform the steps of 1, 2, 3, and 4 in a loop.

Explanation: In theory, a two-dimensional array should be created to represent the chessboard, but in fact, the problem can be solved with a one-dimensional array through an algorithm. arr[8] = {0,4,7, 5,2,6,1.3 } //The subscript corresponding to arr indicates which row, that is, which queen, arr[i]=val, val indicates the i+1th queen, and is placed in the val+1th column of the i+1th row.

It is easier to judge whether any two queens are in the same row and column, but it seems difficult to judge whether they are on the same slash. In fact, there is a rule here. Suppose the coordinates of any two queens are (i, j) and ( n, m), if two queens are on the same slash, then |i - n| = |j - m|.

Java code implementation

public class Queue8 {
    
    
    public static void main(String[] args) {
    
    
        FindQueue8Self findQueue8 = new FindQueue8Self();
        findQueue8.check(0);
    }
}

class FindQueue8Self {
    
    
    //    定义皇后的数量
    int queueAmount = 8;
    //    记录每一个皇后在棋盘上的位置,下标表示行,值表示列
    int[] queueSite = new int[queueAmount];
    //    记录8皇后在棋盘上摆法有多少种
    int count = 0;

    //递归的方法
    public void check(int n) {
    
    
//        当n = 8时,8个皇后都找好位置了,打印出8个皇后摆的位置,记录摆法次数,然后递归回溯。
        if (n == queueAmount) {
    
    
            print();
            return;
        } else {
    
    
            for (int i = 0; i < queueAmount; i++) {
    
    
//                把当前皇后摆放在第一列,第二列....,第八列
                queueSite[n] = i;
//                判断是否会有冲突,若有冲突则将当前皇后放在下一列,若无冲突,则开始在下一行开始摆放下一个皇后。
                if (judge(n)) {
    
    
                    check(n + 1);
                }
            }
        }

    }

    private boolean judge(int n) {
    
    
//        判断当前皇后和之前已经摆放好的皇后是否在同一行、同一列和同一斜线上
        for (int i = 0; i < n; i++) {
    
    
//            queueSite[i] == quequeSite[n] 判断是否在同一列
//            Math.abs(n - i) == Math.abs(queueSite[n] - queueSite[i] 判断是否在同一斜线上
            if (queueSite[i] == queueSite[n] || Math.abs(n - i) == Math.abs(queueSite[n] - queueSite[i])) {
    
    
                return false;
            }
        }
        return true;
    }

    //打印出8个皇后摆的位置,记录摆法次数
    private void print() {
    
    
        count++;
        System.out.print("第" + count + "次8皇后在棋盘上的摆放位置:");
        for (int site : queueSite) {
    
    
            System.out.print(site + " ");
        }
        System.out.println();
    }

}

Test Results

insert image description here

There are a total of 92 ways to arrange the eight queens.

Guess you like

Origin blog.csdn.net/weixin_37977006/article/details/129385260