Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
public class Solution {
static int[] col;
static int count;
public static void main(String[] args) {
System.out.print(totalNQueens(2));
}
public static int totalNQueens(int n) {
col = new int[n];
count = 0;
nqueens(0, n);
return count;
}
public static void nqueens(int colIndex, int n) {
if (colIndex == n) {
count++;
return;
}
for (int i = 0; i < n; i++) {
col[colIndex] = i;
if (valid(colIndex)) {
nqueens(colIndex + 1, n);
}
}
}
private static boolean valid(int colIndex) {
for (int i = 0; i < colIndex; i++) {
// 行不可能重复,列如果重复或者对角线重复
if (col[i] == col[colIndex]
|| Math.abs(col[i] - col[colIndex]) == colIndex - i) {
return false;
}
}
return true;
}
}