以前就听说过八皇后问题,没学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;
}