Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
a DFS search will be exponential increase in terms of N. But use the symmetric property, we could cut the search tree to half of its original size.
Basic implementation, Pass large tests around 980 ms
class Solution {
void recur_solve(int n, int &ret, vector<int> &queens, int cur){
if(cur == n){
ret = ret+1;
return;
}
for(int j=0; j<n; j++){
int pre;
for(pre = 0; pre < cur; pre++)
if(queens[pre] == j || j-queens[pre] == cur - pre || j-queens[pre] == pre - cur)
break;
if(pre == cur){
queens[cur] = j;
recur_solve(n, ret, queens, cur+1);
}
}
}
public:
int totalNQueens(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> queens(n);
int ret = 0;
for(int j=0;j<n/2; j++){
queens[0] = j;
recur_solve(n, ret, queens, 1);
}
ret *= 2;
if(n&1==1){
queens[0] = n/2;
recur_solve(n, ret, queens, 1);
}
return ret;
}
};
To fast index is the key. For example, in the previous code, when we are trying to calculate whether column j could be used to put in row i, we need to check from rows from 0~i-1, if any queen is put on column j. If we have an array to annotate if col j is used, it will be faster.
So an updated version could pass the large test by 504 ms, just adding the usage array.
Similarly, if we add diag usage, we could speed up and pass within 240 ms
class Solution {
void recur_solve(int n, int &ret, vector<int> &queens, vector<int> &usage, vector<int> &diag_lr_usage, vector<int> &diag_rl_usage, int cur){
if(cur == n){
ret = ret+1;
return;
}
for(int j=0; j<n; j++){
if(usage[j] || diag_lr_usage[cur+j] || diag_rl_usage[n-1-j+cur] )
continue;
queens[cur] = j;
usage[j] = diag_lr_usage[cur+j] = diag_rl_usage[n-1-j+cur] = 1;
recur_solve(n, ret, queens, usage, diag_lr_usage, diag_rl_usage, cur+1);
usage[j] = diag_lr_usage[cur+j] = diag_rl_usage[n-1-j+cur] = 0;
}
}
public:
int totalNQueens(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> queens(n);
vector<int> usage(n);
vector<int> diag_lr_usage(2*n-1);
vector<int> diag_rl_usage(2*n-1);
for(int i=0; i<n; i++)
usage[i] = 0;
for(int i=0; i<2*n-1; i++){
diag_lr_usage[i] = 0;
diag_rl_usage[i] = 0;
}
int ret = 0;
for(int j=0;j<n/2; j++){
queens[0] = j;
usage[j] = diag_lr_usage[j] = diag_rl_usage[n-1-j] = 1;
recur_solve(n, ret, queens, usage, diag_lr_usage, diag_rl_usage, 1);
usage[j] = diag_lr_usage[j] = diag_rl_usage[n-1-j] = 0;
}
ret *= 2;
if(n&1==1){
queens[0] = n/2;
usage[n/2] = diag_lr_usage[n/2] = diag_rl_usage[n-1-n/2] = 1;
recur_solve(n, ret, queens, usage, diag_lr_usage, diag_rl_usage, 1);
}
return ret;
}
};
Some code is really very fast:
http://discuss.leetcode.com/questions/230/n-queens-ii