以前就聽說過八皇后問題,沒學BFS的時候,完全沒有頭緒,學了BFS後,也沒想起這道題,前幾天偶偶又看到了這道題,於是心血來潮,決定用BFS遍歷找出所有解(方法很拙,勿噴),採用的數據結構感覺也不是很好,每個point裏面都有一個矩陣,浪費了大量的空間(我也沒想到更好的方法),歡迎有想法的提出改進的地方。附上代碼吧:
#include <iostream>
#include <cstring>
#include <queue>
#include <iostream>
#include <string>
using namespace std;
struct point {
int x; //橫座標
int y; //縱座標
bool m[8][8]; //矩陣標記
string path; //記錄一種方法,如 04752613 表示(0,0)(1,4)(2,7)(3,5)(4,2)....
point(int x_, int y_) : x(x_), y(y_) {}
point() : x(0), y(0) {}
};
//初始化point中的矩陣
void initialize(point& temp) {
for (int i = 0; i < 8; i++)
for (int j = 0; j < 8; j++)
temp.m[i][j] = false;
}
//爲那些不能走的點做上標記
void doFlag(point& p) {
for (int i = 0; i < 8; i++) {
p.m[p.x][i] = true;
p.m[i][p.y] = true;
}
int i = 1, x1 = p.x, y1 = p.y;
while (x1-i >=0 || y1 - i >= 0 || x1+i <= 7 || y1+i <= 7) {
if (x1-i >= 0 && y1-i >= 0)
p.m[x1-i][y1-i] = true;
if (x1-i >= 0 && y1+i <= 7)
p.m[x1-i][y1+i] = true;
if (x1+i <= 7 && y1-i >= 0)
p.m[x1+i][y1-i] = true;
if (x1+i <= 7 && y1+i <= 7)
p.m[x1+i][y1+i] = true;
i++;
}
}
vector<string> vt; //記錄每一種方法
int count_ = 0; //記錄總數
queue<point> que; //主要用於BFS
//廣度優先遍歷
void BFS() {
for (int i = 0; i < 8; i++) {
point temp(0, i);
temp.path = temp.path+static_cast<char>(i+'0');
initialize(temp);
doFlag(temp);
que.push(temp);
}
while (que.front().path.length() < 9) {
point ft = que.front();
int len = ft.path.length();
if (len == 8) {
vt.push_back(ft.path);
count_++;
}
que.pop();
for (int i = 0; i < 8 && len != 8; i++) {
if (!ft.m[len][i]) {
point temp = ft;
temp.x++;
temp.y = i;
temp.path = temp.path+static_cast<char>(i+'0');
doFlag(temp);
que.push(temp);
}
}
}
}
//打印方法
void printMap(string str) {
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (j == str[i] - '0')
cout << 'O' << ' ';
else
cout << 'X' << ' ';
}
cout << endl;
}
cout << endl;
}
int main() {
BFS();
for (vector<string>::iterator it = vt.begin(); it != vt.end(); it++)
printMap(*it);
cout << "total: " << count_ << endl;
return 0;
}