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.."] ]
八皇后问题的关键是每个皇后不在同一列同一行,并且不在同一对角线。那么首先我们可以默认每个皇后不在同一行,即每一行一个皇后。用一个状态数组status保存每行的皇后所在的列数,此时对于每个皇后可以放置的列数是0~n-1遍历,并且检查该行之前放置的皇后的列数位数会不会导致当前皇后与其他皇后引起攻击。因此用valid函数检查此行填写的列数是否合法,如果合法则往下走填写后面行的列数,当填写完所有行的列数,此时就得到一个合法的解。但是此时得到的不是string的表达形式,需要通过changeToString函数转换成string的形式。
class Solution {
public:
void changeToString(vector<int> &status,vector<vector<string> >&result)
{
int n = status.size();
vector<string> temp;
for(int i=0;i<n;i++)
{
string s = "";
for(int j=0;j<n;j++)
{
if(status[i] != j)
s += '.';
else
s += 'Q';
}
temp.push_back(s);
}
result.push_back(temp);
}
bool valid(int cols,int row,int n, vector<int> &status)
{
for(int i=0;i<row;i++)
{
if(status[i] == cols || abs(status[i]-cols) == abs(i-row))
return false;
}
return true;
}
void getQueens(int row,int n,vector<int> &status,vector<vector<string> >&result)
{
if(row == n) //此时表示一个合法的皇后棋盘已经产生
{
changeToString(status,result);
}else{
for(int i= 0;i<n;i++)
{
if(valid(i,row,n,status))
{
status[row] = i;
getQueens(row+1,n,status,result);
status[row] = -1;
}
}
}
}
vector<vector<string>> solveNQueens(int n) {
vector<vector<string> > result;
if(n <= 0) return result;
vector<int>status(n,-1);
getQueens(0,n,status,result);
return result;
}
};