请用c++写一段回溯法求得n皇后问题
时间: 2024-01-18 17:03:55 浏览: 81
以下是使用C++实现的n皇后问题的回溯算法:
```cpp
#include <iostream>
#include <vector>
using namespace std;
void printSolution(const vector<int>& queens) {
for (int i = 0; i < queens.size(); ++i) {
for (int j = 0; j < queens.size(); ++j) {
cout << (queens[i] == j ? "Q" : ".");
}
cout << endl;
}
cout << endl;
}
bool isSafe(const vector<int>& queens, int row, int col) {
for (int i = 0; i < row; ++i) {
// check if a queen exists in the same column or diagonal
if (queens[i] == col || abs(i - row) == abs(queens[i] - col)) {
return false;
}
}
return true;
}
void solveNQueens(vector<int>& queens, int row, int& count) {
if (row == queens.size()) {
// found a solution
++count;
printSolution(queens);
return;
}
for (int i = 0; i < queens.size(); ++i) {
if (isSafe(queens, row, i)) {
queens[row] = i;
solveNQueens(queens, row + 1, count);
}
}
}
int main() {
int n;
cout << "Enter the size of the chessboard: ";
cin >> n;
vector<int> queens(n);
int count = 0;
solveNQueens(queens, 0, count);
cout << "Total solutions: " << count << endl;
return 0;
}
```
该算法使用一个vector来存储每一行皇后所在的列数。solveNQueens函数从第0行开始逐行遍历,对于每一行,它尝试在所有列中找到一个安全位置放置皇后。如果找到了安全位置,就递归调用solveNQueens函数解决下一行。如果所有行都被放置了皇后,就找到了一个解。
阅读全文