[InterviewBit] NQueens

NQueens

  • Time : O(n^3)
  • Space : O(n^2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
void helper(int n, int now, int dig, int rdig, int col, vector<vector<string>>& res, vector<string>& build) {
if(n == now) res.push_back(build);
else {
for(int i = 0; i < n; i++) {
if(dig & (1<<i)) continue;
if(rdig & (1<<i)) continue;
if(col & (1<<i)) continue;
int ndig = dig | (1<<i);
int nrdig = rdig | (1<<i);
int ncol = col | (1<<i);
build.push_back(string(i,'.') + "Q" + string(n-i-1,'.'));
helper(n,now+1,ndig>>1, nrdig<<1, ncol, res, build);
build.pop_back();
}
}
}
vector<vector<string> > Solution::solveNQueens(int A) {
vector<vector<string>> res;
helper(A, 0, 0, 0, 0, res, vector<string>() = {});
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/30/PS/interviewbit/nqueens/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.