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;
}
}
}

本文介绍了一种解决N皇后问题的有效算法。该算法通过跟踪三个数组(水平、垂直和对角线)来确保皇后之间的不冲突放置。利用深度优先搜索(DFS)策略递归地放置皇后,并计算可行方案的数量。
345

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



