这种题应该见过不少了,脑子里的第一个反应就是BFS!就好象走迷宫一样嘛,求最短的路径。判重可以用hash表,将8个数转成一个8位数然后模一个大数。至于BFS就不说了,维护一个队列就好了~
#include<fstream>
#include<string.h>
using namespace std;
bool hash[170537];
struct node
{
int data[9];
int pre;//记录前驱
int cont;//记录步数
char step;//记录所用的变换
};
node q[50000];
ifstream fin("msquare.in");
ofstream fout("msquare.out");
int change(int a,int b,int c,int d,int e,int f,int g,int h)
{
return((a*10000000+b*1000000+c*100000+d*10000+e*1000+f*100+g*10+h)%170537);
}
void print(int a,int k)//递归输出
{
if(k)
{
print(q[a].pre,k-1);
fout<<q[a].step;
}
}
int main()
{
int a1,a2,a3,a4,a5,a6,a7,a8;
fin>>a1>>a2>>a3>>a4>>a5>>a6>>a7>>a8;
memset(hash,0,sizeof(hash));
int final=change(a1,a2,a3,a4,a8,a7,a6,a5);
hash[change(1,2,3,4,8,7,6,5)]=true;
if(change(1,2,3,4,8,7,6,5)==final)
{
fout<<0<<endl<<endl;
return 0;
}
int front=1,rare=1;
int temp[9],f;
q[1].data[1]=1; q[1].data[2]=2; q[1].data[3]=3; q[1].data[4]=4;
q[1].data[5]=8; q[1].data[6]=7; q[1].data[7]=6; q[1].data[8]=5;
q[1].cont=0;
q[1].pre = -1;
while(front<=rare)
{
memcpy(temp,q[front].data,sizeof(temp));
swap(temp[1],temp[5]);
swap(temp[2],temp[6]);
swap(temp[3],temp[7]);
swap(temp[4],temp[8]);
f=change(temp[1],temp[2],temp[3],temp[4],temp[5],temp[6],temp[7],temp[8]);
if(!hash[f])
{
rare++;
memcpy(q[rare].data,temp,sizeof(temp));
q[rare].pre=front;
q[rare].cont=q[front].cont+1;
q[rare].step='A';
hash[f]=true;
if(f==final)
break;
}
memcpy(temp,q[front].data,sizeof(temp));
swap(temp[4],temp[3]);
swap(temp[3],temp[2]);
swap(temp[2],temp[1]);
swap(temp[8],temp[7]);
swap(temp[7],temp[6]);
swap(temp[6],temp[5]);
f=change(temp[1],temp[2],temp[3],temp[4],temp[5],temp[6],temp[7],temp[8]);
if(!hash[f])
{
rare++;
memcpy(q[rare].data,temp,sizeof(temp));
q[rare].pre=front;
q[rare].cont=q[front].cont+1;
q[rare].step='B';
hash[f]=true;
if(f==final)
break;
}
memcpy(temp,q[front].data,sizeof(temp));
swap(temp[6],temp[7]);
swap(temp[7],temp[3]);
swap(temp[3],temp[2]);
f=change(temp[1],temp[2],temp[3],temp[4],temp[5],temp[6],temp[7],temp[8]);
if(!hash[f])
{
rare++;
memcpy(q[rare].data,temp,sizeof(temp));
q[rare].pre=front;
q[rare].cont=q[front].cont+1;
q[rare].step='C';
hash[f]=true;
if(f==final)
break;
}
front++;
}
fout<<q[rare].cont<<endl;
print(rare,q[rare].cont);
fout<<endl;
return 0;
}