#include using namespace std; class Solution { public: vector> solveNQueens(int n) { vector> res; vector stack(n); vector solution(n, string(n, '.')); dfs(n, 0, stack, solution, res); return res; } private: void dfs(int n, int row, vector &stack, vector &solution, vector> &res) { if (row == n) { res.push_back(solution); } else { for (int i = 0; i < n; i++) { if (row == 0 || !conflict(stack, row, i)) { solution[row][i] = 'Q'; stack[row] = i; dfs(n, row + 1, stack, solution, res); solution[row][i] = '.'; } } } } bool conflict(vector &stack, int row, int col) { for (int i = 0; i < row; i++) { if (col == stack[i] || abs(row - i) == abs(col - stack[i])) { return true; } } return false; } }