一次AC,我以为会超呢。
#include<stdio.h>
#include<string.h>
#include<queue>
#include<iostream>
using namespace std;
int s,e,mark[10000],d[2]={1,-1};
struct node
{
int a[5],num,step;
void change()
{
num=a[1]*1000+a[2]*100+a[3]*10+a[4];
}
};
int pd(int x)
{
if(x>0&&x<=4)
return 1;
return 0;
}
void bfs()
{
queue<node> q;
node cur,p;
for(int i=4;i>=1;i--)
{
cur.a[i]=s%10;
s/=10;
}
cur.step=0;
cur.change();
q.push(cur);
while(!q.empty())
{
cur=q.front();
/*for(int i=1;i<=4;i++)
printf("%d",cur.a[i]);
printf("\n");*/
q.pop();
if(cur.num==e)
{
printf("%d\n",cur.step);
return ;
}
for(int i=1;i<=4;i++)
{
for(int j=0;j<2;j++)//加一和减一的情况
{
p=cur;
p.a[i]+=d[j];
if(p.a[i]==10)
p.a[i]=1;
if(p.a[i]==0)
p.a[i]=9;
p.change();
p.step+=1;
if(!mark[p.num])
{
q.push(p);
mark[p.num]=1;
}
}
for(int j=0;j<2;j++)//和相邻的位互换,记得判断是否出界
{
p=cur;
if(pd(i+d[j]))
swap(p.a[i],p.a[i+d[j]]);
p.change();
p.step+=1;
if(!mark[p.num])
{
q.push(p);
mark[p.num]=1;
}
}
}
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d",&s);
scanf("%d",&e);
memset(mark,0,sizeof(mark));
mark[s]=1;
bfs();
}
return 0;
}