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

N-Queens II

2013-12-15 14:45 295 查看
这个题的解法很巧妙,如果直接照搬N-Queens的代码,会发现由于本题输入数据规模变大,导致超时。因此有一个好方法,我们只考虑第0行,有一个明显的对称规律,即如果第0行的皇后可以放在位置i,那么将其放在位置n - 1 - i也是可以的;如果放在位置i不合法,那么关于中心对称的位置n - 1 - i也是不合法的。由此,我们可以将整个运算量减半。

class Solution {
public:
int totalNQueens(int n) {
int total = 0;
if (n == 0)
return total;
string s(n, '.');
vector<string> tmp(n, s);
helper(n, 0, total, tmp);
return total;
}
void helper(int n, int i, int &total, vector<string> &tmp) {
if (i == n) {
total++;
return;
}
if (i == 0) {
for (int j = 0; j < n / 2; ++j) {
if (isValid(n, i, j, tmp)) {
tmp[i][j] = 'Q';
helper(n, i + 1, total, tmp);
tmp[i][j] = '.';
}
}
total *= 2;
if (n % 2 != 0) {
if (isValid(n, i, n / 2, tmp)) {
tmp[i][n / 2] = 'Q';
helper(n, i + 1, total, tmp);
tmp[i][n / 2] = '.';
}
}
return;
}
for (int j = 0; j < n; ++j) {
if (isValid(n, i, j, tmp)) {
tmp[i][j] = 'Q';
helper(n, i + 1, total, tmp);
tmp[i][j] = '.';
}
}
}
bool isValid(int n, int i, int j, vector<string> &tmp) {
for (int p = 0; p < i; ++p)
if (tmp[p][j] == 'Q')
return false;
int p = i - 1, q = j - 1;
while (p >= 0 && q >= 0) {
if (tmp[p][q] == 'Q')
return false;
p--;
q--;
}
p = i - 1;
q = j + 1;
while (p >= 0 && q < n) {
if (tmp[p][q] == 'Q')
return false;
p--;
q++;
}
return true;
}
};
http://oj.leetcode.com/problems/n-queens-ii/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: