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

[leetcode 52] N-Queens II

2015-01-11 09:58 267 查看
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) {
this->res = 0;
this->col = vector<int>(n,0);
this->main_diag = vector<int>(2*n,0);
this->anti_diag = vector<int>(2*n,0);
vector<int> path(n,0);
dfs(path, 0);
return this->res;
}
private:
int res;
vector<int> col;
vector<int> main_diag;
vector<int> anti_diag;
void dfs(vector<int> &path, int row) {
const int N = path.size();
if (row == N) {
++this->res;
return;
}
for (int i = 0; i < N; i++) {
bool ok = col[i] == 0 && main_diag[row+i]==0 && anti_diag[row-i+N]==0;
if(!ok) {
continue;
}
path[row] = i;
col[i] = main_diag[row+i]= anti_diag[row-i+N]= 1;
dfs(path,row+1);
col[i] = main_diag[row+i]= anti_diag[row-i+N]= 0;
}
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: