N皇后问题
- 通过递归回溯来实现n皇后的摆放位置,下面是自己实现的代码,思路写在代码注释里,可以详细看看代码。
class Solution {
public:
void remark(int x,int y,vector<vector<int>> &mark)
{
if(x >= mark.size() || y >= mark.size())
{
return;
}
mark[x][y] = 1;
for(int i = 1;i < mark.size();i++)
{
for(int j = 0;j < 8;j++)
{
int new_x = x + i*dx[j];
int new_y = y + i*dy[j];
if(new_x >= 0 && new_x < mark.size() && new_y >= 0 && new_y < mark.size())
{
mark[new_x][new_y] = 1;
}
}
}
}
void generate(int k,int n,
vector<string> &location,
vector<vector<string>> &result,
vector<vector<int>> &mark)
{
if(k == n)
{
result.push_back(location);
return;
}
for(size_t i = 0;i < n;i++)
{
if(mark[k][i] != 1)
{
location[k].replace(i,1,"Q");
vector<vector<int>> tmp_mark = mark;
remark(k,i,mark);
generate(k+1,n,location,result,mark);
location[k].replace(i,1,".");
mark = tmp_mark;
}
}
}
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> result;
vector<vector<int>> mark;
vector<string> location;
for(int i = 0;i < n;i++)
{
mark.push_back(vector<int> (n,0));
location.push_back(string (n,'.'));
}
generate(0,n,location,result,mark);
return result;
}
private:
const int dx[8] = {-1,1,0,0,-1,-1,1,1};
const int dy[8] = {0,0,-1,1,-1,1,-1,1};
};