直接暴力广搜所有可能的情况,先等于的就是最短的,用vis[]数组标记访问过的数字,搜索的姿势我是这样的,改变每一位上的数的值,放进队列。而且最终一定存在这样的路径,然而,不能给出证明
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
int x,y;
int vis[10010];
struct point
{
int x;
int cot;
};
queue<point> q;
bool prime(int x)
{
for(int i = 2;i*i<=x;i++)
{
if(x%i==0)
return false;
}
return true;
}
void bfs()
{
while(q.size())
q.pop();
point t;
t.x = x;
t.cot = 0;
q.push(t);
vis[x]=1;
point hd;
int i,j;
int stat;
while(q.size())
{
t = q.front();
q.pop();
if(t.x==y)
{
cout<<t.cot<<endl;
return ;
}
for(i=1;i<=1000;i*=10)
{
for(j=0;j<10;j++)
{
if(i==1000&&j==0)
continue;
hd.x = t.x/(i*10)*(i*10)+t.x%i+j*i;
if(vis[hd.x]==0&&prime(hd.x))
{
hd.cot = t.cot+1;
vis[hd.x]=1;
q.push(hd);
}
}
}
}
return ;
}
int main()
{
int t;
cin>>t;
while(t--)
{
cin>>x>>y;
memset(vis,0,sizeof(vis));
bfs();
}
return 0;
}