1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| class Solution { public: vector<vector<string>> solveNQueens(int n) { vector<vector<string>> ret; vector<int> pos(n); backTrack(ret, pos, n - 1, n, 0, 0, 0); return ret; } private: void backTrack(vector<vector<string>>& ret, vector<int>& pos, int curLine, int n, int col, int lx, int rx) { if(curLine < 0) { ret.push_back(getBoard(pos, n)); return; } auto alP = ((1 << n) - 1) & (~(col | lx | rx)); while(alP) { int lastZero = alP & (~alP + 1); int po = __builtin_ctz(lastZero); alP &= alP - 1; pos[curLine] = n - po - 1; backTrack(ret, pos, curLine - 1, n, col | lastZero, (lx | lastZero) << 1, (rx | lastZero) >> 1); } return; } vector<string> getBoard(vector<int> pos, int n) { vector<string> ret; for(auto& p : pos) ret.push_back(getLine(p, n)); return ret; } string getLine(int pos, int n) { string line; int j = 0; for(j; j < pos; ++j) line += "."; line += "Q"; while(++j < n) line += "."; return line; } };
|