您的位置:首页 > 产品设计 > UI/UE

LeetCode 52. N-Queens II

2016-05-16 08:56 585 查看
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
, 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;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: