题意:要求输出N皇后问题的解的个数。
思路:返回解的个数。
class Solution {
public:
vector<vector<string> > re;
int l;
int totalNQueens(int n) {
l = n;
string ts;
vector<string> tes;
for(int i = 0; i < n; i ++) ts += '.';
for(int i = 0; i < n; i ++) tes.push_back(ts);
dfs(tes, 0);
return re.size();
}
void dfs(vector<string> grid, int s) {
if(s == l) {
for(int i = 0; i < l; i ++) {
for(int j = 0; j < l; j ++) {
if(grid[i][j] == 'x') grid[i][j] = '.';
}
}
re.push_back(grid);
return;
}
vector<string> mygrid;
for(int i = 0; i < l; ++ i) {
mygrid = grid;
if(mygrid[s][i] == 'x') continue;
if(mygrid[s][i] == '.') {
mygrid[s][i] = 'Q';
for(int j = s + 1; j < l; j ++) mygrid[j][i] = 'x';
for(int j = i - 1, k = s + 1; j >=0 && k < l; j --, k ++) mygrid[k][j] = 'x';
for(int j = i + 1, k = s + 1; j < l && k < l; j ++, k ++) mygrid[k][j] = 'x';
//for(int it = 0; it < l; it ++) cout << mygrid[it] << endl;
//cout << endl;
dfs(mygrid, s + 1);
}
}
return;
}
};另一种思路是不生成可行解,直接判断是否可行。判断是否可行有O(1)的方法。对于(x, y) 上的某个皇后,满足xi + yi = x + y和 n - xi + yi = x + y的位置都不能放置。
class Solution {
public:
int count;
int l;
int totalNQueens(int n) {
vector<bool> c1(n, false);
vector<bool> c2(n * 2, false);
vector<bool> c3(n * 2, false);
count = 0;
l = n;
dfs(n, c1, c2, c3);
return count;
}
void dfs(int row, vector<bool> c1, vector<bool> c2, vector<bool> c3) {
if(row == 0) count ++;
for(int i = 0; i < l; ++ i) {
if(c1[i] || c2[row + i] || c3[l - row + i]) continue;
else {
c1[i] = true;
c2[row + i] = true;
c3[l - row + i] = true;
dfs(row - 1, c1, c2, c3);
c1[i] = false;
c2[row + i] = false;
c3[l - row + i] = false;
}
}
}
};
本文介绍两种解决N皇后问题的方法:一种通过深度优先搜索生成所有可行解并计数;另一种直接判断解的可行性,利用位操作优化性能。
359

被折叠的 条评论
为什么被折叠?



