這種二維網(wǎng)格規(guī)劃問題书在,一般是遞歸回溯的套路
#include <iostream>
#include <vector>
using namespace std;
int count = 0;
vector<vector<bool>> chessboard(8, vector<bool>(8, false));
void print() {
for (int i=0; i<8; ++i) {
for (int j=0; j<8; ++j) {
if (chessboard[i][j]) cout << "☆";
else cout << "★";
}
cout << endl;
}
cout << endl;
}
bool check(int row, int col) {
for (int i=0; i<row; ++i) {
if (chessboard[i][col]) return false;
}
for (int i=row-1, j=col-1; i>=0 && j>=0; --i, --j) {
if (chessboard[i][j]) return false;
}
for (int i=row-1, j=col+1; i>=0 && j<8; --i, ++j) {
if (chessboard[i][j]) return false;
}
return true;
}
void find_place(int row) {
if (row > 7) {
++count;
print();
return;
}
for (int col=0; col<8; ++col) {
if (check(row, col)) {
chessboard[row][col] = true;
find_place(row+1);
chessboard[row][col] = false;
}
}
}
int main() {
find_place(0);
cout << count << endl;
}