Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
Here's the code:
public class Solution {
public int totalNQueens(int n) {
boolean[][] board = new boolean[n][n];
return totalNQueens(board, 0, n);
}
private int totalNQueens(boolean[][] board, int cur, int n) {
int res = 0;
if(cur == n) {
return 1;
}
for(int i = 0; i < n; i++) {
if(!board[cur][i]) {
boolean[][] subboard = board.clone();
for(int r = cur + 1; r < n; r++) {
subboard[r][i] = true;
}
for(int r = cur + 1, c = i - 1; r < n && c >= 0; r++, c--) {
subboard[r][c] = true;
}
for(int r = cur + 1, c = i + 1; r < n && c < n; r++, c++) {
subboard[r][c] = true;
}
res += totalNQueens(subboard, cur+1, n);
}
}
return res;
}
}
The result:
Input:
4
Output:
0
Expected:
2
I can't figure out what's wrong with this code, so please help me, thx in advance.