class Solution {
vector<vector<string> > ans;
public:
bool canPlace(int i,int j,vector<string> &tmp,int n)//check
{
if(i==0) return true;//when place the first line,all cols is OK
for(int k=0;k<=i-1;k++)//check the lines already placed
if(tmp[k][j]=='Q')
return false;
for(int p=0;p<=i-1;p++)//line:already placed from 0 to i-1
for(int q=0;q<=n-1;q++)//col:from 0 to n-1
if( (p-q==i-j || p+q==i+j)
&&(tmp[p][q]=='Q') )//135 and 45
return false;
return true;
}
vector<int> findCols(int i,vector<string> &tmp,int n)//when line is i,find all possible cols
{
vector<int> res;
for(int k=0;k<=n-1;k++)
{
if(canPlace(i,k,tmp,n))
res.push_back(k);
}
return res;
}
void dfs(int level,vector<string> &tmp,int n)//dfs
{
if(level >= n){
ans.push_back(tmp);
return;
}
vector<int> posCols = findCols(level, tmp, n);
int col;
for(int k = 0; k < posCols.size(); k++){
//cannot use k<=posCols.size()-1,otherwise will occur runtime error
col = posCols[k];
tmp[level][col] = 'Q';//do
dfs(level + 1, tmp, n);
tmp[level][col] = '.';//undo
}
}
vector<vector<string> > solveNQueens(int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
ans.clear();
vector<string> tmp(n, string(n,'.'));//string(n,'.') means set one line as '....',and tmp is n*n '.'
dfs(0,tmp,n);
return ans;
}
};
【leetcode】N-Queens
最新推荐文章于 2013-10-29 23:20:42 发布