八皇后遍历共有92种方式

1、8皇后的的遍历代码

package com.cn.test.algorithm;

public class Queue8 {

    int[][] chessboard = new int[8][8];
    int count = 0;

    public void printChessboard(){
        for (int [] one :chessboard){
            for (int i:one){
                System.out.print(i+" ");
            }
            System.out.println();
        }
    }

    public boolean calculateLocation(int row){
        if(row == 8){
            count++;
            System.out.println("成功:"+count);
            printChessboard();
            return true;
        }
        //从第一列开始尝试
        for(int col = 0; col < 8 ;col++){
            //本行验证成功,进行下一行
            if(checkLocation(row,col)){
                chessboard[row][col] = 1;
                calculateLocation(row + 1);
                chessboard[row][col] = 0;
            }
        }
        return false;
    }

    public boolean checkLocation(int row,int col){
        for (int i = 0;i<row;i++){
            //判断是否在同一列
            if(chessboard[i][col] == 1){
                return false;
            }
            //判断是否在同一斜线上
            // 如果在同一斜线下,则满足:|col -x|= |row -i|
            if(col-(row-i) >= 0 && col-(row-i) <8){
                if(chessboard[i][Math.abs(col-(row-i))] == 1){
                    return false;
                }
            }
            if(col+(row-i) >= 0 && col+(row-i)<8){
                if( chessboard[i][Math.abs(col+(row-i))]  == 1 ){
                    return false;
                }
            }

        }
        return true;
    }
    public static void main(String[] args) {
        Queue8 queue8 = new Queue8();
        System.out.println("原棋盘:");
        queue8.printChessboard();
        queue8.calculateLocation(0);
    }
}

计算的结构是共有92种摆法

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值