题目描述
力扣题目传送 N皇后
基本思路:一行一行地去考虑放置皇后
实现方式:
注意细细体会以下两种实现思路的角度的差异,前者是直接的、被题目要求牵着走的思维方式,而后者是有转换的、基于自己已有的稳定的解题经验模式去主动思考而来。
- 直接的实现方式:使用数据结构记录棋盘中每个位置的元素 + 基于待选的位置去一个个判断其同列与同对角线(注意对角线有两种,x + y = k 型 与 x - y = k 型)的所有位置是不是已经放置了元素——》判断时需要遍历检查所有同列、同对角线位置;
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
num = n;
string tem (num, '.');
vector<string> probability = vector<string>(num,tem);//纵向为x;横向为y
dfs(0,probability);
return ans;
}
vector<vector<string>> ans;
int num;
void dfs(int index, vector<string>&cur){
//考虑第index行的皇后的存放位置
// 递归边界
if (index == num) {
ans.emplace_back(cur);
return;
}
// 本层的处理逻辑:逐个列尝试
for (int i = 0; i < num; i++){
bool unable = false;
// 列符合条件判断
for(int row = 0; row < index ; row++) {
if(cur[row][i]=='Q') {
unable = true;
break;
}
}
if(unable) continue;
// 斜线(两条)符合条件判断
for(int add = -num + 1; add < num ; add++) {
int y = i + add;
int x1 = index + add;
int x2 = index - add;
if(y >= num || y < 0) continue;
if(x1 >= 0 && x1 < num && cur[x1][y] == 'Q') {
unable = true;
break;
}
if(x2 >= 0 && x2 < num && cur[x2][y] == 'Q') {
unable = true;
break;
}
}
if(unable) continue;
// 递归 + 还原现场
cur[index][i] = 'Q';
dfs(index + 1,cur);
cur[index][i] = '.';
}
return;
}
};
-
改进的实现方式:记录已经存放的元素的位置信息 + 记录每个已经放置的元素,每次只需检查待放的位置是否符合条件——》判断时只需要检查相应的记录容器即可(即全排列问题增加了约束条件)
-
约束条件的处理:利用对角线上位置的特性(同一条对角线上的元素的横纵坐标的和或差为相同的值),使用标记容器来实现快速检查某一位置是否合法;
-
容器的选择:都是 int 映射到 bool 型,由于对角线的key存在负值的情况并且key值并不从0/1开始连续取值,所以需要使用对于key更加灵活的map来实现对角线的记录;而列的key值就是就是简单常规的0-n,使用vecto记录即可;
class Solution { public: vector<vector<string>> solveNQueens(int n) { num = n; cols = vector<int>(n); usedCol = vector<bool>(n,false); dfs(0); return ans; } private: int num; vector<int>cols; //记录每一行的皇后存放的列数 vector<vector<string>>ans; // 记录 vector<bool>usedCol; //记录某一列是否使用 unordered_map<int,bool>usedLine1; //记录某一x+y=k型对角线是否使用 unordered_map<int,bool>usedLine2; //记录某一x-y=k型对角线是否使用 vector<string>trans(){ // 根据cols中记录的数据转换成题目要求返回的形式的答案 vector<string> result(num,string(num,'.')); for (int row = 0; row < num; row++) result[row][cols[row]] = 'Q'; return result; } void dfs(int row){ // 边界 if(row == num){ ans.emplace_back(trans()); return; } // 本层的处理逻辑 for(int col = 0; col < num; col++){ if(!usedCol[col] && !usedLine1[row+col] && !usedLine2[row-col]){ // 下一层递归 cols[row] = col; usedCol[col] = true; usedLine1[row+col] = true; usedLine2[row-col] = true; dfs(row + 1); // 还原现场 usedCol[col] = false; usedLine1[row+col] = false; usedLine2[row-col] = false; } } return; } };
-