问题 J: 八数码问题
时间限制: 5 Sec 内存限制: 128 MB提交: 143 解决: 80
[ 提交][ 状态][ 讨论版]
题目描述
八数码问题,即在一个3×3的矩阵中有8个数(1至8)和一个空格,现在要你从一个状态转换到另一个状态,每次只能移动与空格相邻的一个数字到空格当中,问题是要你求从初始状态移动到目标状态所需的最少步数。如下图所示。
1 | 2 | 3 |
| 1 | 2 | 3 |
8 | 0 | 4 |
| 7 | 8 | 4 |
7 | 6 | 5 |
| 0 | 6 | 5 |
初始状态 目标状态
如上图所示的数据以矩阵形式给出。现在给出分别代表初始状态和目标状态的两个3*3的矩阵,请给出两个矩阵相互转化的最少步数。
输入
第1行-第3行:3个用空格分隔的整数,代表初始状态相应位置的数字,0代表空格
第4行-第6行:3个用空格分隔的整数,代表终止状态相应位置的数字,0代表空格
输出
第1行:一个整数,最小转换步数,如不能到相互转化则输出"Impossible"
样例输入
1 2 3
8 0 4
7 6 5
1 2 3
7 8 4
0 6 5
样例输出
2
提示
#include <iostream>
#include <queue>
#include <cstdio>
#include <set>
#include <cstring>
using namespace std;
typedef int state[9];
state st[1000010],end1; //st相当于二维数组
int dis[1000010];
set <int> ly; //set维护st
void table() {
ly.clear();
}
int try_insert(int a) {
int s=0;
for(int j=0; j<9; j++)
s=s*10+st[a][j];
if(ly.count(s)) return 0; //利用stl去重,是最容易实现的
ly.insert(s);
return 1;
}
const int dir[4][2]= {{1,0},{0,1},{-1,0},{0,-1}};
int bfs() {
table();
int fr=1,re=2;
while(fr<re) {
state& s =st[fr];
if(!memcmp(s,end1,sizeof(s))) return fr;
int z;
for(z=0; z<9; z++) if(!s[z]) break;
int x=z/3; //转为二维空间的行
int y=z%3; // 转为二维空间的列
for(int i=0; i<4; i++) {
int newx=x+dir[i][0];
int newy=y+dir[i][1];
int newz=newx*3+newy;
if(newx>=0 && newx <3 && newy>=0 && newy<3) {
state &t=st[re];
memcpy(t,s,sizeof(t));
t[newz]=s[z];
t[z]=s[newz];
dis[re]=dis[fr]+1;
if(try_insert(re)) re++; //如果没有重复出现,尾指针re向后移位。如果重复,则仍停在原来的位置。
}
}
fr++;
}
return 0;
}
int main() {
int ans=0;
for(int i=0; i<9; i++) {
scanf("%d",&st[1][i]);
}
for(int i=0; i<9; i++) {
scanf("%d",&end1[i]); //最终目标
}
ans=bfs();
if(ans>0) printf("%d\n",dis[ans]);
else
printf("Impossible\n");
}