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:
int sum = 0;
vector<int> pos;//记录第 i 个皇后的位置
vector<int> can;//can[i] = 0表示可以放置
vector<vector<string>> res;
vector<string> tres;
void f(int i,int n)//放置第 i 行
{
int flag = 0;
if(i == n)
{
tres.clear();
for(int k=0;k<n;k++)
{
string t = "";
for(int j=0;j<n;j++)
{
if(pos[k] == j)
t += 'Q';
else
t += '.';
}
tres.push_back(t);
}
res.push_back(tres);
sum++;
return;
}
can.clear();
for(int j=0;j<n;j++)
can.push_back(0);
for(int j=0;j<i;j++)
{
can[pos[j]] = 1;
if(i+pos[j]-j < n)
can[i+pos[j]-j] = 1;
if(i <= pos[j]+j)
can[pos[j]+j-i] = 1;
}
for(int j=0;j<n;j++)
{
if(can[j] == 0)
{
flag = 1;
if(pos.size() < i+1)
pos.push_back(j);
else
pos[i] = j;
f(i+1,n);
//还原 can 数组
can.clear();
for(int k=0;k<n;k++)
can.push_back(0);
for(int k=0;k<i;k++)
{
can[pos[k]] = 1;
if(i+pos[k]-k < n)
can[i+pos[k]-k] = 1;
if(i <= pos[k]+k)
can[pos[k]+k-i] = 1;
}
}
}
if(flag == 0)
return;
}
vector<vector<string>> solveNQueens(int n)
{
f(0,n);
return res;
}
};