Get the idea from this post: https://developers.google.com/optimization/puzzles/queens
We only to track three arrays. One is horizontally, one is vertically, one is diagonally.
Horizontally is main[2 * n - 1], Vertically is col[n], diagonally is anti[2 * n - 1];
int totalNQueens(int n) {
vector<bool> col(n, true);
vector<bool> anti(2*n-1, true);
vector<bool> main(2*n-1, true);
int count = 0;
dfs(0, col, main, anti, count);
return count;
}
void dfs(int i, vector<bool> &col, vector<bool>& main, vector<bool> &anti, int &count) {
if (i == col.size()) {
count++;
return;
}
for (int j = 0; j < col.size(); j++) {
if (col[j] && main[i+j] && anti[i+col.size()-1-j]) {
col[j] = main[i+j] = anti[i+col.size()-1-j] = false;
dfs(i+1, col, main, anti, count);
col[j] = main[i+j] = anti[i+col.size()-1-j] = true;
}
}
}