心得:
N皇后:std::vector<std::string> path(n, std::string(n, '.'));构造一个由'.'组成的字符串。
第一题、重新安排形成 LeetCode332 (没做)
第二题、N皇后 LeetCode https://leetcode.cn/problems/n-queens/
n皇后问题是回溯算法解决的经典问题,但是用回溯解决多了组合、切割、子集、排列问题之后,遇到这种二维矩阵还会有点不知所措。
首先来看一下皇后们的约束条件:
- 不能同行
- 不能同列
- 不能同斜线
确定完约束条件,来看看究竟要怎么去搜索皇后们的位置,其实搜索皇后的位置,可以抽象为一棵树。
下面我用一个 3 * 3 的棋盘,将搜索过程抽象为一棵树,如图:
一行一行的试不同的位置。因此可以用row == n作为终止条件。判断位置是否合法的isValid函数中,只需要判断已有的列,45度角和135度角有没有元素。
class Solution {
public:
vector<vector<string>> res;
void backtracking(int n, int row, vector<string>& path){
if(row == n){
res.push_back(path);
return;
}
//for(int col = 0; col <= row;)
for(int col = 0; col < n; col++){
if(isValid(n, row, col, path)){
path[row][col] = 'Q';
//backtracking(n, row, path);
backtracking(n, row + 1, path);
path[row][col] = '.';
}
}
return;
}
bool isValid(int n, int row, int col, vector<string>& path){
for(int i = 0; i < row; i++){//检查列
if(path[i][col] == 'Q') return false;
}
for(int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--){//检查45度
if(path[i][j] == 'Q') return false;
}
//for(int i = col - 1, j = row + 1; i >= 0 && j >= 0; i--, j++){//检查135度
for(int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++){//检查135度
if(path[i][j] == 'Q') return false;
}
return true;
}
vector<vector<string>> solveNQueens(int n) {
res.clear();
std::vector<std::string> path(n, std::string(n, '.'));
backtracking(n, 0, path);
return res;
}
};