from : https://leetcode.com/problems/n-queens-ii/
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
public class Solution {
private int n;
private int total;
private int[] queue;
public int totalNQueens(int n) {
init(n);
traverse(0);
return total;
}
private void traverse(int k) {
if(k == n) {
++total;
return;
}
for(int i=0; i<n; ++i) {
boolean valid = true;
for(int j=0; j<k; ++j) {
if(queue[j] == i || Math.abs(queue[j] - i) == k - j) {
valid = false;
break;
}
}
if(valid) {
queue[k] = i;
traverse(k+1);
}
}
}
private void init(int n) {
total = 0;
queue = new int[n];
this.n = n;
}
}
public class Solution {
private int N, ans;
private int[] position;
public int totalNQueens(int n) {
if (n < 1) {
return 0;
}
init(n);
takeRow(0);
return ans;
}
private void takeRow(int k) {
if (k == N) {
++ans;
return;
}
for (int j = 0; j < N; ++j) {
boolean valid = true;
for (int i = 0; i < k && valid; ++i) {
if (position[i] == j || Math.abs(position[i] - j) == k - i) {
valid = false;
}
}
if (valid) {
position[k] = j;
takeRow(k + 1);
}
}
}
private void init(int n) {
ans = 0;
N = n;
position = new int[n];
}
}