经典题

ref

http://blog.csdn.net/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;
    }
}

优质内容筛选与推荐>>
1、[WinForms]
2、MongoDB(课时22 过期索引)
3、VirtualBox 共享文件夹设置
4、〖Python〗-- 设计模式
5、家庭记账本开发记录(4)


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn