N-Queens I & II

本文提供了一种解决N皇后问题的有效算法实现。通过递归回溯的方法,在n×n的棋盘上放置n个皇后,使得任意两个皇后不会在同一行、同一列或相同的对角线上。文章给出了完整的Java代码实现,包括输出所有可能的解决方案和计算解决方案的数量。

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

经典题

ref

http://blog.youkuaiyun.com/u011095253/article/details/9158473

public class Solution {
    public ArrayList<String[]> solveNQueens(int n) {
        ArrayList<String[]> res = new ArrayList<String[]>();
        if(n<=0) return res;
        int[] loc = new int[n];
        helper(res,loc,0,n);
        return res;
    }
    public void helper(ArrayList<String[]> res, int[] loc, int curRow, int n){
        if(curRow==n) {
            printBd(res,loc, n);
        }else{
            for(int i=0;i<n;i++){
                loc[curRow] = i;
                if(isVal(loc,curRow)){
                    helper(res,loc,curRow+1,n);
                }
            }
        }
    }
    public boolean isVal(int[] loc, int curR){
        for(int i=0;i<curR;i++){
            if((loc[i]==loc[curR] )|| (Math.abs(loc[i]-loc[curR])==(curR-i)))
                return false;
        }
        return true;
    }
    public void printBd(ArrayList<String[]> res, int[] loc, int n){
        String[] sol = new String[n];
        for(int i=0;i<n;i++){
            String t = new String();
            for(int j=0;j<n;j++){
                if(loc[i]==j){
                    t += "Q";
                }else
                    t += ".";
            }
            sol[i] = t;
        }
        res.add(sol);
    }
}

 II 要求输出结果个数,小修改即可

public class Solution {
    public int totalNQueens(int n) {
        if(n<=0) return 0;
        int[] res = new int[1];
        int[] loc =  new int[n];
        helper(res, loc, 0, n);
        return res[0];
    }
    public void helper(int[] res, int[] loc, int curR, int n){
        if(curR==n) res[0]++;
        else{
        for(int i=0;i<n;i++){
            loc[curR] = i;
            if(isVal(loc, curR)){
                helper(res, loc, curR+1, n);
            }
        }
        }
    }
    public boolean isVal(int[] loc, int curR){
        for(int i=0;i<curR;i++){
            if((loc[i]==loc[curR])|| Math.abs(loc[i]-loc[curR])==curR-i){
                return false;
            }
        }
        return true;
    }
}

 

转载于:https://www.cnblogs.com/jiajiaxingxing/p/4446927.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值