N-Queens
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens’ placement, where ‘Q’ and ‘.’ both indicate a queen and an empty space respectively.
For example,
There exist two distinct solutions to the 4-queens puzzle:
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
简单粗暴的理解,题目的意思就是,给出各个棋子彼此不挨着的所有方案,就是每个棋子旁边必须都有空格~
Answer:
class Solution {
public:
typedef vector<string> VS;//vector容器,VS保存string
typedef vector<VS> VVS;//vector容器,VSS保存VS
typedef vector<int> VI;//vector容器,VI保存int
VVS solveNQueens(int n) {
VVS solutions;//某种方案
VI solution(n);//第n种方案
solveNQueensImpl(0, &solution, &solutions);
return solutions;
}
private:
void solveNQueensImpl(int i, VI* _solution, VVS* _solutions) {
VI& solution = *_solution;
VVS& solutions = *_solutions;
int n = solution.size();
if (i == n) solutions.push_back(solToStrings(solution));
else {
// For each column...
for (int j = 0; j < n; ++j) {
// Skip if there is another queen in this column or diagonals
if (isAvailable(solution, i, j)) {
solution[i] = j;
solveNQueensImpl(i+1, &solution, &solutions);
}
}
}
}
bool isAvailable(const VI& solution, int i, int j) {
for (int k = 0; k < i; ++k) {
if (j == solution[k] || abs(i-k) == abs(j-solution[k])) return false;
}
return true;
}
VS solToStrings(const VI& sol) {
int n = sol.size();
VS sol_strings(n);
for (int i = 0; i < n; ++i) {
sol_strings[i] = string(n, '.');
sol_strings[i][sol[i]] = 'Q';
}
return sol_strings;
}
};