Java实现-N皇后问题2

来源:互联网 发布:软件游戏猎手下载 编辑:程序博客网 时间:2024/06/08 01:52

根据n皇后问题,现在返回n皇后不同的解决方案的数量而不是具体的放置布局。

样例

比如n=4,存在2种解决方案

class Solution {    /**     * Calculate the total number of distinct N-Queen solutions.     * @param n: The number of queens.     * @return: The total number of distinct solutions.     */    public int totalNQueens(int n) {        //write your code here        if(n<1){return 0;}int []record=new int[n];return process1(0,record,n);    }    private static int process1(int i,int []record,int n){if(i==n){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);}}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;}};