八皇后问题回溯法非递归c++
时间: 2023-11-18 17:52:48 浏览: 109
以下是非递归实现八皇后问题的C++代码:
```c++
#include <iostream>
#include <stack>
using namespace std;
bool check(int row, int col, int* chessboard) {
for (int i = 0; i < row; i++) {
if (col == chessboard[i] || row - i == col - chessboard[i] || row - i == chessboard[i] - col) {
return false;
}
}
return true;
}
int eightQueens() {
int count = 0;
int chessboard[8] = {0};
stack<int> s;
s.push(0);
while (!s.empty()) {
int row = s.top() / 8;
int col = s.top() % 8;
s.pop();
if (col == 8) {
continue;
}
if (check(row, col, chessboard)) {
chessboard[row] = col;
if (row == 7) {
count++;
} else {
for (int i = 0; i < 8; i++) {
s.push((row + 1) * 8 + i);
}
}
}
}
return count;
}
int main() {
cout << eightQueens() << endl;
return 0;
}
```
阅读全文