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

#34 N-Queens II

2016-08-29 10:09 260 查看
题目描述:

Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.

Have you met this question in a real interview? 

Yes

Example

For n=4, there are 2 distinct solutions.

题目思路:

这题和#33 差不多,把最后的ans改成count就好了。

Mycode(AC = 171ms):

class Solution {
public:
/**
* Calculate the total number of distinct N-Queen solutions.
* @param n: The number of queens.
* @return: The total number of distinct solutions.
*/
int totalNQueens(int n) {
// write your code here
int count = 0;
if (n == 0) return count;

vector<string> sofar;
unordered_set<int> col, diag;
solveNQueens(count, sofar, n, col, diag);
return count;
}

void solveNQueens(int& count,
vector<string>& sofar,
int n,
unordered_set<int>& col,
unordered_set<int>& diag)
{
if (sofar.size() == n) {
count++;
return;
}

string tmp = nDots(n);
for (int i = 0; i < n; i++) {
// if there is no Q in same row, col, and diag,
// then tmp could be a potential ans
if (col.find(i) == col.end() &&
!findDiag(diag, sofar.size(), i, n))
{
col.insert(i);
diag.insert(sofar.size() * n + i);
tmp[i] = 'Q';
sofar.push_back(tmp);

solveNQueens(count, sofar, n, col, diag);

sofar.pop_back();
tmp[i] = '.';
diag.erase(sofar.size() * n + i);
col.erase(i);
}
}
}

// write n '.' in a line
string nDots(int n) {
string str = "";
for (int i = 0; i < n; i++) {
str += ".";
}
return str;
}

// check whether there is Q in diag
bool findDiag(unordered_set<int>& diag, int i, int j, int n) {
for (auto it = diag.begin(); it != diag.end(); it++) {
int row = *it / n;
int col = *it % n;

if (abs(row - i) == abs(col - j)) return true;
}

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