修改10.2.5节 n 皇后问题的算法,要求输出 n 皇后问题的所有解
时间: 2024-05-07 10:21:50 浏览: 125
修改10.2.5节中的算法,可以使用回溯法来求解 n 皇后问题的所有解。回溯法是一种通过穷举所有可能的解来找到所有解的方法。下面是修改后的算法:
```
#include <iostream>
using namespace std;
const int MAXN = 100;
int n;
bool col[MAXN], diag1[MAXN * 2], diag2[MAXN * 2];
int queen[MAXN];
void print() {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (queen[i] == j) cout << "Q ";
else cout << ". ";
}
cout << endl;
}
cout << endl;
}
void dfs(int row) {
if (row == n) {
print();
return;
}
for (int j = 0; j < n; j++) {
if (!col[j] && !diag1[row + j] && !diag2[row - j + n]) {
queen[row] = j;
col[j] = diag1[row + j] = diag2[row - j + n] = true;
dfs(row + 1);
col[j] = diag1[row + j] = diag2[row - j + n] = false;
}
}
}
int main() {
cin >> n;
dfs(0);
return 0;
}
```
在 `dfs` 函数中,当找到一个解时,将其输出即可。这里的 `print` 函数用于输出一个解,它将棋盘上的皇后位置打印出来。运行程序,可以得到所有 n 皇后问题的解。
阅读全文
相关推荐
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)