class Solution {
public:
void print_board(const vector<string> &ch) {
int _pos = 0;
cout << "棋盘:" << endl;
for (const auto &x:ch)
cout << " " << x << endl;
}
void set(vector<string> &board, vector<string> &ch, int x, int y, int n) {
constexpr static int dx[] = {-1, 0, 1, -1, 1, -1, 0, 1};
constexpr static int dy[] = {-1, -1, -1, 0, 0, 1, 1, 1};
board[y][x] = 'Q';
ch[y][x] = 'Q';
for (int orien = 0; orien < 8; ++orien) {
for (int _x = x + dx[orien], _y = y + dy[orien];
_x >= 0 && _x < n && _y >= 0 && _y < n; _x += dx[orien], _y += dy[orien])
if (board[_y][_x] != 'Q')
board[_y][_x] = 'Q';
}
}
void reset(vector<string> &board, vector<string> &ch, int x, int y, int n) {
constexpr static int dx[] = {-1, 0, 1, -1, 1, -1, 0, 1};
constexpr static int dy[] = {-1, -1, -1, 0, 0, 1, 1, 1};
board[y][x] = '.';
ch[y][x] = '.';
for (int orien = 0; orien < 8; ++orien) {
for (int _x = x + dx[orien], _y = y + dy[orien];
_x >= 0 && _x < n && _y >= 0 && _y < n; _x += dx[orien], _y += dy[orien])
if (board[_y][_x] != '.')
board[_y][_x] = '.';
}
}
void solve(int &ans, vector<string> ch, vector<string> _ch, int x, int y, int n) {
if (y == n) {
++ans;
return;
}
for (; x < n; ++x)
if (ch[y][x] != 'Q') {
set(ch, _ch, x, y, n);
solve(ans, ch, _ch, x + 1, y + 1, n);
reset(ch, _ch, x, y, n);
}
}
int totalNQueens(int n) {
int ans = 0;
string t(n, '.');
vector<string> _ch(n, t), ch(_ch);
// for (auto &x:ch)
// cout << x << endl;
solve(ans, ch, _ch, 0, 0, n);
cout << ans;
return ans;
}
};