题目:
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;
}
};
本文深入探讨了N皇后问题的高级应用,不仅展示了如何使用递归和回溯法来解决该问题,而且还介绍了如何计算并返回所有独特的棋盘配置数量。通过详细的代码解析和实例说明,读者可以理解如何在复杂场景下优化算法以求得精确的解决方案数。
233

被折叠的 条评论
为什么被折叠?



