【一天一道】八皇后的递归与非递归

本文详细介绍了使用递归和非递归方法解决经典的八皇后问题。通过两种不同的算法实现,展示了如何在一个8x8的棋盘上放置八个皇后,使得任意两个皇后不会互相攻击。递归方法简洁明了,而非递归方法则更复杂但提供了更深入的理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

递归:

public class eightQueue {
    static int record[] = new int[8];
    static int num = 0;
    static int N = 8;
    public static void main(String []args){
        System.out.println("start*********");
        if(args.length != 0){
            N = Integer.parseInt(args[0]);
        }
        findQueue(0);
        System.out.println(num);

    }
    public static void findQueue(int row){
        if(row == N){
            num++;
            System.out.println("找到第" + num + "个。。。");
            return;
        }else {
            for (int col = 0; col < N; col++) {
                if (checkQueue(row, col)) {
                    record[row] = col;
                    findQueue(row + 1);
                }
            }
        }
    }
    public static Boolean checkQueue(int row, int col){
        for(int i=0; i<row; i++){
            if(record[i] == col || Math.abs(i-row) == Math.abs(col - record[i])){
                return false;
            }
        }
        return true;
    }
}

非递归:

public class eightQueue2 {
    static int record[] = new int[8];
    static int num = 0;
    static int N = 8;
    public static void main(String []args) {
        findQueue();
        System.out.println(num);
    }

    public static void findQueue(){
        init();
        //非递归的话,假如从第0个皇后开始,到第7个皇后,然后逆推第6个皇后的其他位置,然后。。。然后到第0个皇后的下一个位置,
        //反复循环
        for(int row = 0; row >= 0; ){
            record[row]++;//此时是从0开始的,即1-8列,与下面的N对应,不然就是N-1
            if(record[row] == N){
                //假如第row个皇后的位置到达了8列,说明依然检索完当前皇后,逆推到上一个皇后,标记清零
                record[row] = -1;
                row--;
                continue;
            }
            if(checkQueue(row, record[row])){
                //假如第row个皇后的当前位置与前row个皇后不冲突
                //可以查找下一个皇后了
                row++;
                if(row==N){
                    //假如第N-1个符合,即第7个皇后符合,即最后一个皇后,计数加1,然后逆推道倒数第二个,
                    num++;
                    record[row-1] = -1;
                    row = N-2;
                }
            }
        }
    }
    public static void init(){
        for(int i = 0; i < N; i++){
            record[i] = -1;
        }
    }    public static Boolean checkQueue(int row, int col){
        for(int i=0; i<row; i++){
            if(record[i] == col || Math.abs(i-row) == Math.abs(col - record[i])){
                return false;
            }
        }
        return true;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值