#
问题描述:
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.."]
]
测试代码(c++):
class Solution {
void add_queen(vector<vector<string>>& result,vector<string> res,vector<vector<bool> > index,int n,int row)
{
string s(n,'.');
if(row==n)
{
result.push_back(res);
return;
}
for(int i=0;i<n;i++)
{
if(index[row][i])
continue;
s[i] = 'Q';
res.push_back(s);
add_queen(result,res,edit(index,row+1,i),n,row+1);
s[i] = '.';
res.pop_back();
}
}
vector<vector<bool> > edit(vector<vector<bool> > index,int row,int i)
{
for(int j=row;j<index.size();j++)
{
index[j][i] = true;
if(i-j+row-1>=0)
{
index[j][i-j+row-1] = true;
}
if(i+j-row+1<index.size())
{
index[j][i+j-row+1] = true;
}
}
return index;
}
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> result;
vector<string> res;
vector<vector<bool> > index(n,vector<bool>(n,false));
add_queen(result,res,index,n,0);
return result;
}
};
性能:
参考答案(c++):
class Solution {
public:
int abs(int x, int y)
{
return x>y ? x-y:y-x;
}
bool isSol(vector<int> & nums, int next)
{
for(int row=0; row<next; row++)
{
if(nums[row] == nums[next])
return false;
if(abs(next,row) == abs(nums[next],nums[row]))
return false;
}
return true;
}
void npossibility(vector<int> & pos, int index, vector<vector<int>> & result)
{
for (int i = 0; i<pos.size(); i++)
{
pos[index] = i;
if (isSol(pos, index))
{
if (index == pos.size() - 1)
result.emplace_back(pos);
else
npossibility(pos, index + 1, result);
}
}
} vector<vector<string>> solveNQueens(int n) {
vector<vector<int>> result ;
vector<int> pos (n, 0);
npossibility(pos, 0 , result);
vector<vector<string>> strresult ;
string dotstr (n,'.');
vector<string> str (n, dotstr);
for(auto r:result)
{
vector<string> temp (str);
for(int row=0; row<r.size(); row++)
{
temp[row][r[row]] = 'Q';
}
strresult.emplace_back(temp);
}
return strresult;
}
};
性能:
参考答案(python):
def DFS(queens, xy_dif, xy_sum):
p = len(queens)
if p==n:
result.append(queens)
return None
for q in range(n):
if q not in queens and p-q not in xy_dif and p+q not in xy_sum:
DFS(queens+[q], xy_dif+[p-q], xy_sum+[p+q])
result = []
DFS([],[],[])
return [ ["."*i + "Q" + "."*(n-i-1) for i in sol] for sol in result]