8 queen problem, analysis and code implementation

package org.structure.recursion;

/**
 * 八皇后问题
 * 8皇后问题分析:任意两个皇后不能在同一行、同一列,同一斜线
 * 解决方法:棋盘是8行8列的二维数组,1定义一个皇后在第0行0列,则第二个皇后在第一行中的某个位置(可能有多个位置)。。。直到第8个皇后
 * 2然后选择皇后在第0行的第二个位置,继续查找第二个皇后的位置,。。。直到第8个皇后。
 * 。。。一直重复上述步骤,直到程序运行结束
 * @author cjj_1
 * @date 2020-08-11 14:13
 */
public class EightQueenProblem {
    
    
    static int max = 8;//定义8个皇后
    static int [] arr = new int[max];//定义一个数组存放8皇后:下标表示,皇后所在的行,与第几个皇后;二数组中的值表示皇后所在行中的位置
    static int count=0;//计数8皇后摆放合理的组合次数
    public static void main(String[] args) {
    
    
        check(0);
        System.out.println(count);

    }
    public static void check(int n){
    
    
        if(n==max){
    
    
            count++;
            print();
            return;
        }else{
    
    
            for(int i =0;i<max;i++){
    
    
                arr[n] = i;
                if(judge(n)){
    
    
                    check(n+1);
                }
            }
        }
    }
    //判断第n个皇后是否合法
    //arr[i]==arr[n] 表示判断第n个皇后是否和前面的n-1个皇后在同一列
    //Math.abs(n-i)==Math.abs(arr[n]-arr[i]) 表示第n个皇后是否和第i个皇后是否在同一斜线上
    private static Boolean judge(int n) {
    
    
        for(int i=0;i<n;i++){
    
    
            if(arr[i]==arr[n]||Math.abs(n-i)==Math.abs(arr[n]-arr[i]))
                return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }
//打印出一组8皇后
    private static void print() {
    
    
        for(int i =0;i<arr.length;i++){
    
    
            System.out.printf("%d\t",arr[i]);
        }
        System.out.println();
    }
}

The following figure is the printed result (not complete), a total of 92 results. Each line on the way is a set of 8 queens solution. Each row of data is composed of a one-dimensional array arr, where the subscript i indicates that the i-th queen is in the i-th row, and the corresponding value arr[i] of the subscript is the column of the queen's row.

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_40128696/article/details/107939727