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:
[ [".Q..", // Solution 1 "...Q", "Q...", "..Q."], ["..Q.", // Solution 2 "Q...", "...Q", ".Q.."] ]
思考:回溯。
class Solution {
public:
bool check(vector<int> ans,int k,int i)
{
for(int j=0;j<k;j++)
{
if(ans[j]==i||(abs(i-ans[j])==abs(k-j))) return false;
}
return true;
}
void Queens(vector<vector<string> > &res,vector<int> &ans,int k,int n)
{
for(int i=0;i<n;i++)
{
if(check(ans,k,i))
{
ans[k]=i;
if(k==n-1)
{
vector<string> temp;
for(int j=0;j<n;j++)
{
string str(n,'.');
str[ans[j]]='Q';
temp.push_back(str);
}
res.push_back(temp);
}
else Queens(res,ans,k+1,n);
}
}
}
vector<vector<string> > solveNQueens(int n) {
vector<vector<string> > res;
vector<int> ans(n,0);
Queens(res,ans,0,n);
return res;
}
};