1. 题意描述
2. 题意分析
我以八皇后为例进行分析.
主要有三种思路:
- 思路一: 暴力出奇迹
- 从
种格子中选出任意
个格子拜访皇后, 检查每一种摆法的可能性
- 一共
种摆法 (大概是
种摆法)
- 从
- 思路二: 根据题意减小暴力程度
- 很显然, 每一行只能放一个皇后, 所以共有
种摆法 (
种), 检查每一种摆法的可能性
- 很显然, 每一行只能放一个皇后, 所以共有
- 思路三: 回溯法
- 回溯
剪枝
- 回溯
3. AC Code
int Q[10] = { 0 }; // 存放每一个皇后的列号
int ways = 0; // 解法数
vector<vector<string>> ans;
class Solution {
public:
bool isValid(int row, int col) {
// 检查第row行第col列是否可以放置皇后
for (int i = 0; i < row; i++) {
if (Q[i] == col) return false;
if (row - i == abs(col - Q[i])) return false;
}
return true;
}
void place(int row, int n, vector<vector<string>>& ans) {
// 从第row行开始放置皇后
if (row == n) {
vector<string> tmp;
for (int i = 0; i < n; i++) {
string s;
for (int j = 0; j < Q[i]; j++) s += ".";
s += "Q";
for (int j = Q[i] + 1; j < n; j++) s += ".";
tmp.push_back(s);
}
ans.push_back(tmp);
return;
}
for (int col = 0; col < n; col++) {
if (isValid(row, col)) {
Q[row] = col;
place(row + 1, n, ans);
}
}
}
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> ans;
place(0, n, ans);
return ans;
}
};