-51. N-Queens QuestionEditorial Solution My Submissions
Total Accepted: 57241
Total Submissions: 215678
Difficulty: Hard
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 Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> res;
vector<int> vis(n,0),resid(n,0);
vector<string> vs;
solveNQueens2(n,res,resid,vs,vis,0);
return res;
}
void solveNQueens2(int n,vector<vector<string>> &res,vector<int> resid,vector<string> vs,vector<int> vis,int j) {
if(j==n){
res.push_back(vs);
}
else{
string s(n,'.');
for(int i=0;i<n;++i){
if(vis[i]==0){
vis[i]=1;
s[i] = 'Q';
resid[j]=i;
if(!isLegal(resid,j,i)){
s[i] = '.';
vis[i]=0;
continue;
}
vs.push_back(s);
solveNQueens2(n,res,resid,vs,vis,j+1);
vs.erase(vs.end()-1);
s[i] = '.';
vis[i]=0;
}
}
}
}
bool isLegal(const vector<int> &resid,int row,int col)
{
for(int i=0;i<row;++i){//是否在同一对角线上
if(abs(col-resid[i])==abs(row-i))return false;
}
return true;
}
};