广度优先搜索。
#include <iostream>
#include <math.h>
#include <string>
#include <deque>
using namespace std;
int pr[10000];
int flag[10000];
void prime() {
int i,j,k;
for ( i=1001;i<=9997;i++ ) {
k=0;
for ( j=2;j<=sqrt(i);j++ ) {
if ( i%j==0 ) {
k++;
break;
}
}
if ( k==0 ) {
pr[i]=1;
}
else {
pr[i]=0;
}
}
}
int main()
{
int n,last,ctr,temp,i,j,a,b;
deque <string> data[2];
//int num[10]={0,1,2,3,4,5,6,7,8,9};
string s,t1,t2;
prime();
// for ( i=1001;i<=9997;i++ )
// cout << pr[i] << " ";
cin >> n;
while ( n-- ) {
cin >> s >> last;
temp=(s[0]-'0')*1000+(s[1]-'0')*100+(s[2]-'0')*10+s[3]-'0';
if ( temp==last )
cout << 0 << endl;
else {
for ( i=1001;i<=9997;i++ )
flag[i]=0;
a=0;
b=1;
data[a].push_back(s);
flag[temp]=1;
ctr=0;
while ( temp!=last ) {
ctr++;
while ( !data[a].empty() ) {
t1=data[a].front();
data[a].pop_front();
for ( j=0;j<10;j++ ) {
t2=t1;
temp=(t2[0]-'0')*1000+(t2[1]-'0')*100+(t2[2]-'0')*10+j;
if ( temp==last )
break;
else {
if ( pr[temp]==1&&flag[temp]==0 ) {
t2[3]=j+'0';
data[b].push_back(t2);
flag[temp]=1;
}
}
}
if ( temp==last )
break;
for ( j=0;j<10;j++ ) {
t2=t1;
temp=(t2[0]-'0')*1000+(t2[1]-'0')*100+j*10+t2[3]-'0';
if ( temp==last )
break;
else {
if ( pr[temp]==1&&flag[temp]==0 ) {
t2[2]=j+'0';
data[b].push_back(t2);
flag[temp]=1;
}
}
}
if ( temp==last )
break;
for ( j=0;j<10;j++ ) {
t2=t1;
temp=(t2[0]-'0')*1000+j*100+(t2[2]-'0')*10+t2[3]-'0';
if ( temp==last )
break;
else {
if ( pr[temp]==1&&flag[temp]==0 ) {
t2[1]=j+'0';
data[b].push_back(t2);
flag[temp]=1;
}
}
}
if ( temp==last )
break;
for ( j=1;j<10;j++ ) {
t2=t1;
temp=j*1000+(t2[1]-'0')*100+(t2[2]-'0')*10+t2[3]-'0';
if ( temp==last )
break;
else {
if ( pr[temp]==1&&flag[temp]==0 ) {
t2[0]=j+'0';
data[b].push_back(t2);
flag[temp]=1;
}
}
}
if ( temp==last )
break;
}
swap(a,b);
}
data[a].clear();
data[b].clear();
cout << ctr << endl;
}
}
return 0;
}