dfs + backtracing 典型题目
需要注意的地方:
1.剪枝放在了下行状态的循环内部
2.需要判别当前位置可否放置皇后,当前列,两条对角线都是需要考虑的
class Solution {
public:
bool setable(const vector<string> &cur, const vector<int> & col_used, int row,int col, int n)
{
if (col_used[col] == 1)
return false;
int i = row - 1;
int j = col - 1;
while (i >= 0 && j >= 0)
{
if (cur[i][j] == 'Q')
return false;
--i;
--j;
}
i = row - 1;
j = col + 1;
while (i >= 0 && j < n)
{
if (cur[i][j] == 'Q')
return false;
--i;
++j;
}
return true;
}
void dfs(vector<vector<string>> &vct, vector<string> &cur, vector<int> & col_used, int row, int n)
{
if (row >= n)
{
vct.push_back(cur);
return;
}
for (int i = 0; i<n; ++i)
{
// try to set queen at a[row][i];
if (setable(cur, col_used, row, i,n))
{
col_used[i] = 1;
cur[row][i] = 'Q';
dfs(vct, cur, col_used, row + 1, n);
cur[row][i] = '.';
col_used[i] = 0;
}
}
}
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> vct;
if (n <= 0)
return vct;
vector<string> cur(n, string(n, '.'));
vector<int> col_used(n, 0);
dfs(vct, cur, col_used, 0, n);
return vct;
}
};
唯一不同的地方在于:不需要存储最终的放置方案,只需要统计方案的个数,所以将所有vct替换为int ans,vct.push_back(cur) 替换为 ++ans ,最后将ans返回即可(只有返回值代表的含义不同,当然若是偷懒的话返回vct.size() 也不是不可以)
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。