The n-queenspuzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Givenan integer n, return all distinct solutions tothe n-queens puzzle.
Eachsolution contains a distinct board configuration of the n-queens'placement, where 'Q' and '.' both indicate a queen and an empty space respectively.
Forexample,
There exist two distinct solutions to the 4-queens puzzle:
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
还是n皇后问题,不过这一题要求输出所有的可能的结果,以矩阵的形式输出结果,所以这一题除了需要一个储存选择的数组以外,还需要一个存储最终结果的数组,
同样,这一题也有简单解法,使用一个solution数组,存储同斜线的可能发生非法的皇后位置的和和位置的差,这样能够省去判断斜线是否能够互相攻击的函数,这样能够提升算法的效率
以后在做递归的题目的时候要注意,在进入下一层递归的时候可能会修改一些设置,当递归返回的时候需要还原这些设置,这里需要注意的是这些设置的返回需要按照顺序返回,在进入下一层递归是按照怎样的顺序设置,在递归返回的时候就需要按照怎样的顺序还原!
class Solution {
public:
void p(vector<vector<string>> &result,vector<bool> &solution,vector<string> &mark, vector<int> &select,int t,int n)
{
if (t == n)
{
result.push_back(mark);
}
for (int i = t; i < n; i++)
{
if (solution[3*n+t - select[i]] && solution[t + select[i]])
{
solution[3 * n + t - select[i]] = false;
solution[t + select[i]] = false;
swap(select[t], select[i]);
mark[t][select[t]] = 'Q';
p(result,solution, mark, select, t + 1, n);
mark[t][select[t]] = '.';
swap(select[t], select[i]);
solution[t + select[i]] = true;
solution[3 * n + t - select[i]] = true;
}
}
}
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> result;
vector<bool> solution(4 * n, true);
vector<string> mark;
vector<int> select;
string u;
u.insert(0, n, '.');
for (int i = 0; i < n; select.push_back(i), i++, mark.push_back(u));
p(result, solution, mark, select, 0, n);
return result;
}
};