Input: n = 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown.
class Solution
{
public:
bool isSafe(int row, int col, int n, vector<vector<int>> &v)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (v[i][j] == 1)
{
if (i == row || j == col || i + j == row + col || i - j == row - col)
{
return false;
}
}
}
}
return true;
}
void findPos(int row, int n, vector<vector<int>> &v, int &count)
{
if (row == n)
{
count++;
return;
}
for (int i = 0; i < n; i++)
{
if (isSafe(row, i, n, v))
{
v[row][i] = 1;
findPos(row + 1, n, v, count);
v[row][i] = 0;
}
}
return;
}
int totalNQueens(int n)
{
vector<vector<int>> v(n, vector<int>(n, 0));
int count = 0;
findPos(0, n, v, count);
return count;
}
};