class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
use.resize(n);
mmap.resize(n,vector<int>(n));
count = 0;
dfs(0,n);
return ret;
}
private:
vector<int> use;
vector<vector<int>> mmap;
vector<vector<string>> ret;
int count;
void dfs(int row,int n)
{
if(row == n) {
vector<string> vec;
for(int k = 0;k<n;k++)
{
string temp;
for(int t = 0;t<n;t++)
{
if(mmap[k][t]==0)
temp.push_back('.');
else temp.push_back('Q');
}
vec.push_back(temp);
}
ret.push_back(vec);
return ;
}
for(int i = 0;i<n;i++)
{
if(use[i] == 0)
{
if(canput(row,i,n))
{
mmap[row][i] = 1;
use[i] = 1;
dfs(row+1,n);
use[i] = 0;
mmap[row][i] = 0;
}
}
}
}
bool canput(int row,int col,int n)
{
int i = row-1,j = col-1;
while(1){
if(i<0 || j<0) break;
if(mmap[i][j] == 1)
return false;
else i--,j--;
}
i = row-1,j=col+1;
while(1){
if(i<0 || j >= n) break;
if(mmap[i][j] == 1)
return false;
else i--,j++;
}
return true;
}
};
LeetCode 51. N-Queens
最新推荐文章于 2022-01-01 11:01:46 发布