Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
Analysis: DFS. The basic logic is the same as N-Queens.
public class Solution {
public int totalNQueens(int row, int ways, int[] existQueens) {
if(row==existQueens.length) return 1;
for(int col=0; col<existQueens.length; col++) {
boolean satisfied = true;
for(int i=0; i<=row; i++) {
if(existQueens[i]==col || Math.abs(i-row)==Math.abs(existQueens[i]-col)) {
satisfied = false;
break;
}
}
if(satisfied) {
existQueens[row] = col;
ways += totalNQueens(row+1, 0, existQueens);
existQueens[row] = Integer.MIN_VALUE;
}
}
return ways;
}
public int totalNQueens(int n) {
int[] existQueens = new int[n];
Arrays.fill(existQueens, Integer.MIN_VALUE);
return totalNQueens(0, 0, existQueens);
}
}