leetcode-52. N-Queens II
题目:
>
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
跟上一题一样,比上一题简单。51-N-Queens I
public class Solution {
private int ret = 0;
public int totalNQueens(int n) {
boolean [][] mat = new boolean[n][n];
helper(mat,0);
return ret;
}
private void helper( boolean[][] mat,int len){
if(len==mat.length){
ret++;
return ;
}
for(int i=0;i<mat.length;i++){
if(verify(mat,len,i)){
mat[len][i] = true;
helper(mat,len+1);
mat[len][i] = false;
}
}
}
private boolean verify(boolean[][] mat, int ni , int nj){
for(int i = 0 ; i<ni ; i++){
if(mat[i][nj]) return false;
if(ni-i-1>=0 && nj-i-1>=0 && mat[ni-i-1][nj-i-1]) return false;
if(ni-i-1>=0 && nj+i+1<mat.length && mat[ni-i-1][nj+i+1]) return false;
}
return true;
}
}