Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
class Solution {
public:
bool isValid(vector<string>& svec, int i, int j, int n)
{
for(int h = 0; h < j; ++h)
{
if(svec[i][h] == 'Q')
{
return false;
}
}
for(int k = 0; k < i; ++k)
{
if(svec[k][j] == 'Q')
{
return false;
}
}
int k = i - 1, h = j - 1;
while(k >= 0 && h >= 0)
{
if(svec[k][h] == 'Q')
{
return false;
}
k--;
h--;
}
k = i + 1;
h = j + 1;
while(k < n && h < n)
{
if(svec[k][h] == 'Q')
{
return false;
}
++k;
++h;
}
k = i - 1, h = j + 1;
while(k >= 0 && h < n)
{
if(svec[k][h] == 'Q')
{
return false;
}
--k;
h++;
}
k = i + 1, h = j - 1;
while(k < n && h >= 0)
{
if(svec[k][h] == 'Q')
{
return false;
}
++k;
--h;
}
return true;
}
void help(vector<string>& svec, int dep, int n, int& sum)
{
if(dep == n)
{
//vsvec.push_back(svec);
++sum;
return;
}
for(int i = 0; i < n; ++i)
{
if(isValid(svec, i, dep, n))
{
svec[i][dep] = 'Q';
help(svec, dep + 1, n, sum);
svec[i][dep] = '.';
}
}
}
int totalNQueens(int n)
{
if(n <= 0)
{
return 0;
}
string s = "";
for(int i = 0; i < n; ++i)
{
s += '.';
}
vector<string> svec(n, s);
int sum = 0;
help(svec, 0, n, sum);
return sum;
}
};