Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
经典N皇后问题,直接dfs即可
class Solution {
public:
int ans;
bool check(int x1, int y1 , int x2 , int y2)
{
if(x1 == x2 || y1 == y2)
return false;
if( (x1-x2) == (y1-y2) || (x1-x2) == (y2-y1))
return false;
return true;
}
void dfs(int now , vector<pair<int,int> > &m, int n)
{
if(now==n+1)
{
ans++;
return;
}
for(int i=1;i<=n;i++)
{
bool flag = true;
for(int j=0;j<m.size() && flag;j++)
{
int x = m[j].first , y = m[j].second;
if(!check(now,i,x,y))
flag=false;
}
if(flag)
{
m.push_back(make_pair(now,i));
dfs( now + 1 , m , n );
m.pop_back();
}
}
}
int totalNQueens(int n)
{
ans = 0;
vector<pair<int,int> > m;
dfs(1,m,n);
return ans;
}
};