注意判断前导0
注意改变temp1的多次使用的值时
要先暂时存储一下然后使用完之后恢复
#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
#define maxn 10000
bool isprime[maxn]= {0};
void prime()
{
isprime[0]=isprime[1]=1;
for(int i=2; i<maxn; i++)
for(int j=i*i; j<maxn; j+=i)
isprime[j]=1;
}
struct node
{
int x,step;
} temp1,temp2;
int n,m,t[5],ans,cnt,temp;
void bfs()
{
bool vis[maxn]= {0};
queue<node>q;
temp1.x=n;
temp1.step=0;
q.push(temp1);
vis[temp1.x]=1;
while(!q.empty())
{
temp1.x=q.front().x;
temp1.step=q.front().step;
if(temp1.x==m)
{
ans=temp1.step;
return ;
}
t[0]=temp1.x/1000;
t[1]=temp1.x%1000/100;
t[2]=temp1.x%100/10;
t[3]=temp1.x%10;
q.pop();
for(int i=0; i<4; i++)
{
temp=t[i];
for(int j=0; j<10; j++)
{
if((i==0||i==3)&&j==0)
continue;
if(j!=temp)
{
t[i]=j;
temp2.x=t[0]*1000+t[1]*100+t[2]*10+t[3];
temp2.step=temp1.step+1;
if(!vis[temp2.x]&&!isprime[temp2.x])
{
q.push(temp2);
vis[temp2.x]=1;
}
}
}
t[i]=temp;
}
}
}
int main()
{
prime();
int t;
cin>>t;
while(t--)
{
cin>>n>>m;
bfs();
cout<<ans<<endl;
}
}