直接上代码,使用标准回溯算法
private int count = 0;
public int totalNQueens(int n) {
put(0, new int[n]);
return count;
}
public void put(int row, int[] arr) {
if (row == arr.length) {
count++;
} else if (row < arr.length) {
for (int i = 0; i < arr.length; i++) {
if (judgeIndex(row, i, arr)) {
arr[row] = i;
put(row + 1, arr);
arr[row] = 0;
}
}
}
}
public boolean judgeIndex(int row, int k, int[] arr) {
for (int i = 0; i < row; i++) {
if (arr[i] == k || Math.abs(row - i) == Math.abs(arr[i] - k)) {
return false;
}
}
return true;
}