码迷,mamicode.com
首页 > 其他好文 > 详细

N-Queens I & II

时间:2015-04-22 13:24:36      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:

经典题

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;
    }
}

 

N-Queens I & II

标签:

原文地址:http://www.cnblogs.com/jiajiaxingxing/p/4446927.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!