N-Queens I & II

经典题

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;

    }

}

 

你可能感兴趣的:(UE)