Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
Analysis:
The idea is similar with last questions, the different is not to record the solutions, count the number
Java
public class Solution {
int []A;
int result;
public int totalNQueens(int n) {
A = new int[n];
result = 0;
nqueens(0, n);
return result;
}
public void nqueens(int cur, int n){
if(cur==n) {
result++;
return;
}
else {
for(int i=0;i<n;i++){
A[cur] = i;
if(valid(cur)){
nqueens(cur+1, n);
}
}
}
}
public boolean valid(int r){
for(int i=0;i<r;i++){
if(A[i]==A[r]|| Math.abs(A[i]-A[r])==r-i){
return false;
}
}
return true;
}
}
c++
class Solution {
public:
bool isValidQueens(vector<int> &A,int r){
for(int i=0;i<r;i++){
if((A[i]==A[r])||(abs(A[i]-A[r]))==(r-i))
return false;
}
return true;
}
void nqueens2(int n, int &result, int cur, vector<int> &A){
if(cur == n){
result++;
return;
}else{
for(int i=0;i<n;i++){
A[cur] = i;
if(isValidQueens(A, cur))
nqueens2(n,result,cur+1,A);
}
}
}
int totalNQueens(int n) {
int result =0;
vector<int> A(n,-1);
nqueens2(n,result,0,A);
return result;
}
};