八皇后问题~

/*
 *每个皇后不能在同一行,不能在同一列,也不能在对角线
 * 同一行:每行只放置一个皇后
 *不能在同一列:使用标志数组,如果当前列的值为true表示不可放置
 * 不能再对角线:同样使用标志数组,如果为false则表示已被占领,不可放置
 * 上对角线:行-列+7
 * 下对角线:行+列
 * */

public class test18 {
    // 皇后所在的位置
    static int[] place = new int[8];
    // 标志数组, true为不可放置
    static boolean[] notPlaceable = new boolean[8];
    // 存储结果数量
    static int[] sum = {0};
    // d1数组存储上对角线,d2数组存储下对角线,false认为对角线上有皇后,不可以占领
    static boolean[] d1 = {true, true, true, true, true, true, true, true, true, true, true, true, true, true,true};
    static boolean[] d2 = {true, true, true, true, true, true, true, true, true, true, true, true, true, true,true};
    // 8皇后具体算法
    private static void generate(int n){
        // 每个皇后都有8种可能的列
        for (int col = 0; col < 8; col++) {
            // 判断是否可以放置
            if(!notPlaceable[col] && d1[n-col+7] && d2[n+col]){
                //行数是一个自然递增的过程,我们只需要判断其列
                place[n] = col;  // 在 n 行 col 列摆放皇后
                notPlaceable[col] = true;  // 占领该列
                d1[n-col+7] = false;  // 占领上对角线
                d2[n+col] = false;  // 占领下对角线
                if(n < 7)
                    generate(n+1);//递归算法----递归7次之后求得一种结果8个皇后所在的位置
                else{
                    sum[0]++;  // 解的个数加1
                    myPrint();  // 打印一种结果
                }
                // 回溯用于求其他结果
                notPlaceable[col] = false;
                d1[n-col+7] = true;
                d2[n+col] = true;
            }
        }
    }

    // 打印每种结果
    private static void myPrint(){
        for (int i = 0; i < place.length; i++) {
            System.out.print(place[i]+1 + " "); // 打印结果直接是第几列
        }
        System.out.println();
    }
    // 主函数
    public static void main(String[] args) {
        generate(0); // 求解8皇后
        System.out.println("共有的解法: " + sum[0]);
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

从未止步..

谢谢你的打赏,我会继续努力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值