八皇后问题(回溯算法)



class Queue8{
    static final int MAX_NUM = 8;
    static int chessBoard[][] = new int[MAX_NUM][MAX_NUM];
    //查看落点是否符合规定
    static boolean check(int x,int y){

        for(int i=0;i<y;i++){
            //查看纵向
            if(chessBoard[x][i]==1){
                return false;
            }
            //查看左侧倾斜
            if(x-1-i>=0&&chessBoard[x-1-i][y-1-i]==1){
                return false;
            }
            //查看右侧倾斜
            if(x+1+i<MAX_NUM&&chessBoard[x+1+i][y-1-i]==1){
                return false;
            }

        }
        return true;
    }

    boolean settleQueen(int y){//行数超过8 答案已经出来
        if(y==MAX_NUM){
            return true;
        }


        //遍历当前行,一行一行摆放,其中一列一列遍历,找到合适的位置
        for(int i=0;i<MAX_NUM;i++){

            for(int x =0;x<MAX_NUM;x++){  //这里不太懂,我觉得是chessBoard[y][x]=0
                chessBoard[x][y] = 0;
            }

            if(check(i,y)){
                chessBoard[i][y]=1;
                if(settleQueen(y+1)){
                    return true;
                }
            }

        }
        return false;

    }

    void printChessBoard(){  //i和j有一点点不确定,不知道为啥要转置输出
        for(int j=0;j<MAX_NUM;j++){
            for(int i=0;i<MAX_NUM;i++){
                System.out.print(chessBoard[i][j]);
            }
            System.out.println();
        }
    }


}

class Main {
    public static void main(String[] args) {
        Queue8 queue8 = new Queue8();
        queue8.settleQueen(0);
        queue8.printChessBoard();
    }
}

代码是对的,,但是我还是有点晕,,醒悟了就回来补。。。。

猜你喜欢

转载自blog.csdn.net/h_666666/article/details/84990629