// #51 N皇后问题
class Solution {
vector<vector<string>> result;
vector<string> curPath;
void solveNQueensIter(int curRow, int targetRow, vector<int>& usedCol, unordered_set<int>& usedDiff, unordered_set<int>& usedSum) {
if (curRow == targetRow) {
result.emplace_back(curPath);
return;
}
for (int curCol = 0; curCol < targetRow; curCol++) {
if (usedCol[curCol] == 1) continue;
if (usedDiff.find(curRow - curCol) != usedDiff.end()) continue;
if (usedSum.find(curRow + curCol) != usedSum.end()) continue;
string path(targetRow, '.' );
path[curCol] = 'Q';
curPath.emplace_back(path);
usedCol[curCol] = 1;
usedDiff.insert(curRow - curCol);
usedSum.insert(curRow + curCol);
solveNQueensIter(curRow + 1, targetRow, usedCol, usedDiff, usedSum);
usedDiff.erase(curRow - curCol);
usedSum.erase(curRow + curCol);
usedCol[curCol] = 0;
curPath.pop_back();
}
}
public:
vector<vector<string>> solveNQueens(int n) {
vector<int> usedCol(n, 0);
unordered_set<int> usedDiff, usedSum;
solveNQueensIter(0, n, usedCol, usedDiff, usedSum);
return result;
}
};