题目:
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
class Solution {
public:
int totalNQueens(int n) {
res = 0;
memset(used, false, sizeof(used));
dfs(0, n);
return res;
}
private:
int res;
// a[i]表示第i行的a[i]列有Queen
int a[100];
int used[100];
void dfs(int dep, int maxDep) {
if (dep == maxDep) {
res++;
return;
}
for (int y = 0; y < maxDep; y++) {
if (check(dep, y) && !used[y]) {
used[y] = true;
a[dep] = y;
dfs(dep + 1, maxDep);
used[y] = false;
}
}
}
bool check(int x, int y) {
for (int i = 0; i < x; i++) {
if (abs(i-x) == abs(y-a[i]))
return false;
}
return true;
}
};