Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
same as N-Queens problem, beside count solution instead of construct chessboard
Check problem of N-Queens for detail approach
public class Solution {
int res;
public int totalNQueens(int n) {
helperDFS(n,0,new int[n]);
return res;
}
private void helperDFS(int n,int row,int[] columnForRow){
if(row==n){
res+=1;
return;
}
for(int i=0;i<n;i++){
columnForRow[row]=i;
if(isValid(row,columnForRow)){
helperDFS(n,row+1,columnForRow);
}
}
}
private boolean isValid(int row, int[] columnForRow){
for(int i=0;i<row;i++) {
if (columnForRow[row]==columnForRow[i]
|| Math.abs(columnForRow[row]-columnForRow[i])==row-i) {
return false;
}
}
return true;
}
}