public class Solution {
public static int sum;
public int totalNQueens(int n) {
sum = 0;
int[] usedColumns = new int[n];
placeQueen(usedColumns, 0);
return sum;
}
public void placeQueen(int[] usedColumns, int row) {
int n = usedColumns.length;
if (row == n) {
sum ++;
return;
}
for (int i = 0; i < n; i++) {
if (isValid(usedColumns, row, i)) {
usedColumns[row] = i;
placeQueen(usedColumns, row + 1);
}
}
}
public boolean isValid(int[] usedColumns, int row, int col) {
for (int i = 0; i < row; i++) {
if (usedColumns[i] == col) {
return false;
}
// 这里是判断对角线, 包含两种情况
//row + col == i + usedColumns[i] 移项后就是row - i == usedColumns[i] - col
以及row - col == i - usedColumns[i] 移项后就是 row - i == col - usedColomns[i]
if ((row - i) == Math.abs(col-usedColumns[i])) {
return false;
}
}
return true;
}
}