class Solution {
public:
vector<vector<string>> res_;
bool valid(vector<string>& chessboard, int row, int col) {
for (int j = 0; j < row; j++) {
if (chessboard[j][col] == 'Q') {
return false;
}
}
for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) {
if (chessboard[i][j] == 'Q') {
return false;
}
}
for (int i = row, j = col; i >= 0 && j < chessboard.size(); i--, j++) {
if (chessboard[i][j] == 'Q') {
return false;
}
}
return true;
}
void back_tracking(vector<string> chessboard, int row) {
if (row == chessboard.size()) {
res_.push_back(chessboard);
return;
}
for (int j = 0; j < chessboard[0].size(); j++) {
if (valid(chessboard, row, j)) {
chessboard[row][j] = 'Q';
back_tracking(chessboard, row + 1);
chessboard[row][j] = '.';
}
}
}
vector<vector<string>> solveNQueens(int n) {
vector<string> chessboard(n, string(n, '.'));
back_tracking(chessboard, 0);
return res_;
}
};