#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
struct node
{
int a[4],step;
};
char str[2][5];
int f[4];
bool vis[10][10][10][10];//这里不能在这赋值为0,要在下面赋值
int BFS()//有返回值,用int
{
node now,next;
for(int i=0;i<4;i++)
{
now.a[i]=str[0][i]-'0';
f[i]=str[1][i]-'0';
}
memset(vis,false,sizeof(vis));//在这里对标记初始化
now.step=0;
queue<node>q;
q.push(now);
bool lock;
while(!q.empty())
{
now=q.front();
q.pop();
lock=true;
for(int i=0;i<4;i++)
{
if(now.a[i]!=f[i])
{
lock=false;
break;
}
}
if(lock)
return now.step;
for(int i=0;i<4;i++)//加一
{
next=now;
if(now.a[i]==9)
next.a[i]=1;
else
next.a[i]=now.a[i]+1;
if(!vis[next.a[0]][next.a[1]][next.a[2]][next.a[3]])
{
vis[next.a[0]][next.a[1]][next.a[2]][next.a[3]]=true;
next.step=now.step+1;
q.push(next);
}
}
for(int i=0;i<4;i++)//减一
{
next=now;
if(now.a[i]==1)
next.a[i]=9;
else
next.a[i]=now.a[i]-1;
if(!vis[next.a[0]][next.a[1]][next.a[2]][next.a[3]])
{
vis[next.a[0]][next.a[1]][next.a[2]][next.a[3]]=true;
next.step=now.step+1;
q.push(next);
}
}
for(int i=0;i<3;i++)//交换
{
next=now;
next.a[i]=now.a[i+1];
next.a[i+1]=now.a[i];
if(!vis[next.a[0]][next.a[1]][next.a[2]][next.a[3]])
{
vis[next.a[0]][next.a[1]][next.a[2]][next.a[3]]=true;
next.step=now.step+1;
q.push(next);
}
}
}
//return -1;要不要都行
}
int main()
{
int t;
cin>>t;
while(t--)
{
cin>>str[0]>>str[1];
cout<<BFS()<<endl;
}
return 0;
}
05-20
05-20
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交