1426: [蓝桥杯][历届试题]九宫重排
题目描述
如下面第一个图的九宫格中,放着 1~8 的数字卡片,还有一个格子空着。与空格子相邻的格子中的卡片可以移动到空格中。经过若干次移动,可以形成第二个图所示的局面。
我们把第一个图的局面记为:12345678.
把第二个图的局面记为:123.46758
显然是按从上到下,从左到右的顺序记录数字,空格记为句点。
本题目的任务是已知九宫的初态和终态,求最少经过多少步的移动可以到达。如果无论多少步都无法到达,则输出-1。
输入
输入第一行包含九宫的初态,第二行包含九宫的终态。
输出
输出最少的步数,如果不存在方案,则输出-1。
样例输入
12345678. 123.46758
样例输出
3
#include<iostream>
#include<algorithm>
#include<vector>
#include<set>
#include<cstring>
#include<cstdio>
#define M 1000000
using namespace std;
typedef int type[9];
type qs[M];
type mb;
int front,rear;
int dir[4][2]={-1,0,0,-1,0,1,1,0};
int dis[M]={0};
set<int> vis;
int panchong(int x)
{
int i,sum=0;
for (i=0; i<9; i++)
{
sum = sum*10+qs[x][i];
}
if (vis.count(sum))
{
return 0;
}
vis.insert(sum);
return 1;
}
int bfs()
{
front = 1;
rear = 2;
int i,j,k=0,c,x,y,xx,yy,z,zz;
while (front < rear)
{
type &s = qs[front];
if (memcmp(s,mb,sizeof(mb)) == 0)
{
return front;
}
for (k=0; k<9; k++)
{
if(s[k]==0)
{
z=k;
}
}
x = z/3;
y = z%3;
for (i=0; i<4; i++)
{
xx = x+dir[i][0];
yy = y+dir[i][1];
if(xx>=0 && xx<3 && yy>=0 && yy<3)
{
type &t = qs[rear];
memcpy(t,s,sizeof(s));
zz=xx*3+yy;
t[z] = s[zz];
t[zz] = s[z];
if(panchong(rear))
{
dis[rear] = dis[front]+1;
rear++;
}
}
}
front++;
}
return -1;
}
int main()
{
int i,j,cnt;
char ch[10],ch2[10];
scanf("%s %s",ch,ch2);
for (i=0; i<9; i++)
{
if(ch[i]<='8'&&ch[i]>='0')
qs[1][i]=ch[i]-'0';
else
qs[1][i]=0;
}
for (i=0; i<9; i++)
{
if(ch2[i]<='8'&&ch2[i]>='0')
mb[i]=ch2[i]-'0';
else
mb[i]=0;
}
cnt = bfs();
if(cnt>0)
{
cout<<dis[cnt]<<endl;
}
else
{
cout<<-1<<endl;
}
return 0;
}