与Leetcode51.N_Queen完全一样,甚至II比I还要简单点。
时间复杂度:O(N^2)
C++代码:
class Solution {
int result = 0;
vector<bool> diagTopLeftToBottomRight;
vector<bool> diagTopRightToBottomLeft;
vector<bool> col;
vector<bool> row;
vector<int>queen;
public:
int totalNQueens(int n) {
if (n == 1)
return 1;
if (n < 4)
return 0;
initial(n);
nQueen(n, 0);
return result;
}
void initial(int n)
{
diagTopLeftToBottomRight.resize(2 * n - 1);
diagTopRightToBottomLeft.resize(2 * n - 1);
row.resize(n);
col.resize(n);
for (int i = 0; i < 2 * n - 1; i++)
{
diagTopLeftToBottomRight[i] = diagTopRightToBottomLeft[i] = true;
}
for (int i = 0; i < n; i++)
{
row[i] = col[i] = true;
}
}
bool judge(int x,int y ,int n)
{
if (row[x] == true && col[y] == true &&
diagTopLeftToBottomRight[x - y + n - 1] == true &&
diagTopRightToBottomLeft[x + y] == true)
{
return true;
}
return false;
}
void nQueen(int n, int now)
{
if (now == n)
{
result++;
return;
}
for (int i = 0; i < n; i++)
{
if (judge(now, i,n))
{
row[now] = false;
col[i] = false;
diagTopLeftToBottomRight[now - i + n - 1] = false;
diagTopRightToBottomLeft[now + i] = false;
nQueen(n, now + 1);
row[now] = true;
col[i] = true;
diagTopLeftToBottomRight[now - i + n - 1] = true;
diagTopRightToBottomLeft[now + i] = true;
}
}
}
};