Problem I
八数码
时限:5000ms 内存限制:20000K 总时限:10000ms
描述
在九宫格里放在1到8共8个数字还有一个是空格,与空格相邻的数字可以移动到空格的位置,问给定的状态最少需要几步能到达目标状态(用0表示空格):
1 2 3
4 5 6
7 8 0
输入
输入一个给定的状态。
输出
输出到达目标状态的最小步数。不能到达时输出-1。
输入样例
1 2 3
4 0 6
7 5 8
输出样例
2
#include <iostream>
#include <queue>
#include <map>
using namespace std;
struct rec {
int a[3][3];
int empty_x, empty_y;
bool useful;
int vis;
int step;
};
queue<rec> q;
rec start, end;
map<int, int> visited;
int maze[3][3];
int dx[4] = {0, 0, -1, 1};
int dy[4] = {-1, 1, 0, 0};
void init() { //初始化
int temp = 0;;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cin >> maze[i][j];
start.a[i][j] = maze[i][j];
if (maze[i][j] == 0) {
start.empty_x = i, start.empty_y = j;
}
temp = temp * 10 + maze[i][j];
}
}
start.vis = temp;
start.step = 0;
}
bool isTarget(rec next) {
if (next.a[0][0] == 1 && next.a[0][1] == 2 && next.a[0][2] == 3 && next.a[1][0] == 4 && next.a[1][1] == 5
&& next.a[1][2] == 6 && next.a[2][0] == 7 && next.a[2][1] == 8 && next.a[2][2] == 0) {
return true;
}
return false;
}
rec moveto(rec now, int i) {
rec next;
next.empty_x = now.empty_x + dx[i];
next.empty_y = now.empty_y + dy[i];
if (next.empty_x < 0 || next.empty_x >= 3 || next.empty_y < 0 || next.empty_y >= 3) {
next.useful = false;
return next;
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
next.a[i][j] = now.a[i][j];
}
}
next.a[next.empty_x][next.empty_y] = 0;
next.a[now.empty_x][now.empty_y] = now.a[next.empty_x][next.empty_y];
int temp = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
temp = 10 * temp + next.a[i][j];
}
}
next.vis = temp;
next.useful = true;
return next;
}
int bfs() {
q.push(start);
while (q.size()) {
rec now = q.front();
if (isTarget(now)) {
return now.step;
}
q.pop();
for (int i = 0; i < 4; i++) {
rec next = moveto(now, i);
if (next.useful == true) {
if (!visited[next.vis]) { //该种状态未被访问
visited[next.vis] = 1;
next.step = now.step + 1;
q.push(next);
}
}
}
}
return -1;
}
int main() {
init();
cout << bfs() << endl;
return 0;
}