The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q'
and '.'
both
indicate a queen and an empty space respectively.
For example,
There exist two distinct solutions to the 4-queens puzzle:
這是一道搜索題,使用深度優先搜索就可以解決問題,關鍵是剪枝,也就是每一次放皇后的時候都要檢查之前所放過的皇后的位置是否衝突,是否
再同一列或者是否在同一條斜線上
代碼如下:
class NQueue
{
private:
bool canPlace(vector<int>& beforeQueues,int p)
{
int curRow = (int)beforeQueues.size();
for(int i=0;i<beforeQueues.size();i++)
{
bool flag = ((curRow-i==p-beforeQueues[i])||(curRow-i==beforeQueues[i]-p));
if(flag||(p==beforeQueues[i]))
return false;
}
return true;
}
void generate(vector<string>& result,vector<int> cols)
{
for(int i=0;i<cols.size();i++)
{
string tmp = "";
for(int j=0;j<cols.size();j++)
{
if(j!=cols[i])
tmp+=".";
else
tmp+="Q";
}
result.push_back(tmp);
}
}
void _nqueue(vector<vector<string> >& ret,int row,int n,vector<int> curResult)
{
if(row == n)
{
vector<string> result;
generate(result,curResult);
ret.push_back(result);
}
else
{
for(int i=0;i<n;i++)
{
if(canPlace(curResult,i))
{
vector<int> tmp = curResult;
tmp.push_back(i);
_nqueue(ret,row+1,n,tmp);
}
}
}
}
public:
vector<vector<string> > solveNQueens(int n) {
vector<vector<string> > ret;
vector<int> curResult;
_nqueue(ret,0,n,curResult);
return ret;
}
};