class Solution {
public:
int totalNQueens(int n) {
vector<int>state(n,-1);
dfs(state,0);
return res;
}
void dfs(vector<int>&state,int row)
{
int n=state.size();
if(row==n)
{
res++;
return;
}
for(int col=0;col<n;col++)
{
if(isValid(state,row,col))
{
state[row]=col;
dfs(state,row+1);
}
}
}
bool isValid(vector<int>state,int row,int col)
{
for(int i=0;i<row;i++)
{
if(state[i]==col||abs(row-i)==abs(state[i]-col))
return false;
}
return true;
}
private:
int res=0;
};
网友评论