一道搜索的水题,其实搜索相对其他的来说好掌握一点,因为有个固定的模板可以用去套
题目大意就是数字的变化,一个数字只可以变化到它最相邻的一个素数上去,意思是只变化一位数字,求最短的变化方案
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <queue>
bool mark [10001];
int s[10001],step[10001],ans;
using namespace std;
queue<int >q;
int bfs(int x)
{
int head,c[4],y,i;
if(x==ans)
{
printf("0\n");
return 0;
}
while(!q.empty())
q.pop();
q.push(x);
mark[x]=false;
while(!q.empty())
{
head=q.front();
q.pop();
c[0]=head/1000;
c[1]=(head-c[0]*1000)/100;
c[2]=(head-c[0]*1000-c[1]*100)/10;
c[3]=head%10;
for(i=0;i<=9;i++)
{
if(i!=0)
{
y=1000*i+c[1]*100+c[2]*10+c[3];
if(s[y]&&mark[y]){q.push(y);mark[y]=false;step[y]=step[head]+1;}
}
y=c[0]*1000+100*i+c[2]*10+c[3];
if(s[y]&&mark[y]){q.push(y);mark[y]=false;step[y]=step[head]+1;}
y=c[0]*1000+c[1]*100+i*10+c[3];
if(s[y]&&mark[y]){q.push(y);mark[y]=false;step[y]=step[head]+1;}
y=c[0]*1000+c[1]*100+c[2]*10+i;
if(s[y]&&mark[y]){q.push(y);mark[y]=false;step[y]=step[head]+1;}
}
if(head==ans) printf("%d\n",step[head]);
}
return 0;
}
int main()
{
int i,n,first;
memset(s,0,sizeof(s));
for(i=1000;i<=10000;i++)
for(int j=2;j<=sqrt(i)+1;j++)
{
if(i%j==0) break;
if(j==int(sqrt(i))) s[i]=1;
}
scanf("%d",&n);
while(n)
{
n--;
memset(mark,true,sizeof(mark));
memset(step,0,sizeof(step));
scanf("%d%d",&first,&ans);
bfs(first);
}
return 0;
}