Java实现-N皇后问题1

来源:互联网 发布:淘宝联盟佣金 编辑:程序博客网 时间:2024/06/08 01:06

n皇后问题是将n个皇后放置在n*n的棋盘上,皇后彼此之间不能相互攻击。

给定一个整数n,返回所有不同的n皇后问题的解决方案。

每个解决方案包含一个明确的n皇后放置布局,其中“Q”和“.”分别表示一个女王和一个空位置。

样例

对于4皇后问题存在两种解决的方案:

[

    [".Q..", // Solution 1

     "...Q",

     "Q...",

     "..Q."],

    ["..Q.", // Solution 2

     "Q...",

     "...Q",

     ".Q.."]

]

class Solution {    /**     * Get all distinct N-Queen solutions     * @param n: The number of queens     * @return: All distinct solutions     * For example, A string '...Q' shows a queen on forth position     */    ArrayList<ArrayList<String>> solveNQueens(int n) {        // write your code here        if(n<1){return null;}int []record=new int[n];ArrayList<ArrayList<String>> result=new ArrayList<ArrayList<String>>();int num= process1(0,record,n,result);return result;    }    private static int process1(int i,int []record,int n,ArrayList<ArrayList<String>> result){if(i==n){ArrayList<String> tempList=new ArrayList<String>();StringBuffer s=new StringBuffer();for(int k=0;k<n;k++){s=s.append(".");}for(int k=0;k<record.length;k++){s.setCharAt(record[k], 'Q');tempList.add(s.toString());s.setCharAt(record[k], '.');}result.add(new ArrayList<String>(tempList));return 1;}int res=0;for(int j=0;j<n;j++){if(isValid(record,i,j)){record[i]=j;res+=process1(i+1, record, n,result);}}return res;}private static boolean isValid(int []record,int i,int j){for(int k=0;k<i;k++){if(j==record[k]||Math.abs(record[k]-j)==Math.abs(i-k)){return false;}}return true;}};