51. N-Queens
problem description
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.
Example:
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.
algorithm thought
经典的n皇后问题。使用回溯法解决问题,每次放之前首先判断这个位置是否合法,如果合法,放入这位置。如果不合法判断下个能放的位置。最后如果没有能放的位置的时候,就回溯。
code
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;
}
};
algorithm analysis
这里的时间复杂度我也不是太清楚,查了资料,网上有两种说法,我觉得O(n^n)和O(n!)都有道理。
Last updated