Approach
Depth-first search
For Solvenqueens, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 53 lines of C++ from the credited upstream file solveNQueens.cpp.
- The implementation visibly relies on sequence storage.
- 2 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4class Solution {5 public:6 void addAnswer(int n) {7 vector<string> v;8 9 for(int i = 0; i < n; i++) {10 string s(n, '.');11 s[chess[i]] = 'Q';12 v.push_back(s);13 }14 15 ans.push_back(v);16 }17 18 void dfs(int row) {19 const int N = chess.size();20 if(row == N) {21 addAnswer(N);22 return;23 }24 25 for(int i = 0; i < N; i++) {26 if(cols[i] == 0 && main_diag[row + i] == 0 && anti_diag[row - i + N] == 0) {27 cols[i] = main_diag[row + i] = anti_diag[row - i + N] = 1;28 chess[row] = i;29 dfs(row + 1);30 cols[i] = main_diag[row + i] = anti_diag[row - i + N] = 0;31 }32 }33 }34 35 vector<vector<string> > solveNQueens(int n) {36 cols = vector<int>(n, 0);37 main_diag = vector<int>(2 * n, 0);38 anti_diag = vector<int>(2 * n, 0);39 chess = vector<int>(n, 0);40 41 dfs(0);42 43 return ans;44 }45 46 private:47 vector<vector<string> > ans;48 vector<int> cols;49 vector<int> main_diag;50 vector<int> anti_diag;51 vector<int> chess;52};53