51. N-Queens
Last updated
Last updated
Input: 4
Output: [
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> res;
string t(n,'.');
vector<string> tmp;
for(int i=0;i<n;++i)
tmp.push_back(t);
helper(res,tmp,0);
return res;
}
void helper(vector<vector<string>>& res,vector<string> tmp,int pos){
if(pos==tmp.size()){
res.push_back(tmp);
return;
}
for(int i=0;i<tmp.size();++i){
if(isvalid(pos,i,tmp)){
tmp[pos][i]='Q';
helper(res,tmp,pos+1);
tmp[pos][i]='.';
}
}
}
bool isvalid(int x,int y,vector<string> res){
for(int i=0;i<res.size();++i){
if(res[x][i]=='Q'||res[i][y]=='Q')
return false;
}
int i=x-1,j=y-1;
while(i>=0&&j>=0){
if(res[i--][j--]=='Q')
return false;
}
i=x-1;j=y+1;
while(i>=0&&j<res.size()){
if(res[i--][j++]=='Q')
return false;
}
return true;
}
};