题目地址: http://acm.hdu.edu.cn/showproblem.php?pid=1195
一个标准的宽搜,一点不需要剪枝
需要注意的一点是:交换的时候,这个地方只能交换邻居,我当时看错以为可以任意交换
代码如下:
#include <iostream>
#include <queue>
using namespace std;
int a[5],b[5];
bool visit[10010];
int hashb;
struct xh
{
int d[5];
int t;
}w,ww;
int hash(int x[])
{
int i,sum=0;
for(i=1;i<=4;i++)
sum=sum*10+x[i];
return sum;
}
int add(int n)
{
if(n==9)
return 1;
return n+1;
}
int jian(int n)
{
if(n==1)
return 9;
return n-1;
}
int bfs()
{
int i,j,hashx;
memset(visit,false,sizeof(visit));
queue<xh>q;
for(i=1;i<=4;i++)
w.d[i]=a[i];
w.t=0;
hashx=hash(a);
visit[hashx]=true;
q.push(w);
while(!q.empty())
{
ww=q.front();
q.pop();
if(hash(ww.d)==hashb)
{
printf("%d\n",ww.t);
break;
}
//加一减一
for(i=1;i<=4;i++)
{
w=ww;//加一
w.d[i]=add(w.d[i]);
hashx=hash(w.d);
if(!visit[hashx])
{
visit[hashx]=true;
w.t++;
q.push(w);
}
w=ww;//减一
w.d[i]=jian(w.d[i]);
hashx=hash(w.d);
if(!visit[hashx])
{
visit[hashx]=true;
w.t++;
q.push(w);
}
}
//交换,这个地方只能交换邻居,我当时看错了题目
for(i=1;i<4;i++)
{
w=ww;
swap(w.d[i],w.d[i+1]);
hashx=hash(w.d);
if(!visit[hashx])
{
visit[hashx]=true;
w.t++;
q.push(w);
}
}
}
}
int main()
{
int i,j,n,T;
char c;
cin>>T;
while(T--)
{
for(i=1;i<=4;i++)
{
cin>>c;
a[i]=c-'0';
}
for(i=1;i<=4;i++)
{
cin>>c;
b[i]=c-'0';
}
hashb=hash(b);
bfs();
}
return 0;
}