[LeetCode] N-Queens II

来源:互联网 发布:音频测试软件 编辑:程序博客网 时间:2024/06/07 15:39
[Problem]

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

[LeetCode] N-Queens II - coder007 - Coder007的博客


[Solution]

class Solution {
public:
// is the new Queen valid
bool valid(int row, int column, vector<pair<int, int> > &located){
for(int i = 0; i < located.size(); ++i){
if(located[i].first + located[i].second == row + column || located[i].second - located[i].first == column - row){
return false;
}
}
return true;
}

// search location
int search(bool column[], int n, int mth, vector<pair<int, int> > &located){
int res = 0;

// the last row
if(mth == n - 1){
for(int i = 0; i < n; ++i){
if(column[i] == false && valid(mth, i, located)){
res++;
}
}
}
else{
for(int i = 0; i < n; ++i){
// valid in the ith column
if(column[i] == false && valid(mth, i, located)){

// locate a Queen in (mth, i)
column[i] = true;
located.push_back(make_pair(mth, i));

// search in the next row
int r = search(column, n, mth+1, located);
res += r;

// back
column[i] = false;
located.pop_back();
}
}
}
return res;
}

// n queen
int totalNQueens(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function

// the columns with Queen
bool column[n];
memset(column, false, sizeof(column));

// located Queens
vector<pair<int, int> > located;

// search
return search(column, n, 0, located);
}
};


 说明:版权所有,转载请注明出处。Coder007的博客