题目大意:给出两个四位素数,每次改变只能改四位中的一位,问最少经过几次改变能将第一个数变为第二个数
输入:case个数n(最多不超过100个)
第i个case的两个四位素数(不以0开头)
输出:最少改变次数/impossible
分析:bfs搜索
先打印素数表,再用队列进行bfs搜索。和leetcode127类似。这道题采用count数组记录每个结点的深度,而127没用count数组,而是直接记录遍历的层数,然后在每一层内广度遍历。
代码:转载自http://blog.csdn.net/wangjian8006/article/details/7461966
#include <iostream>
#include <queue>
using namespace std;
#define MAXV 10000
bool prime[MAXV];
void init(){ //对素数打表
int i,j;
for(i=1000;i<=MAXV;i++){
for(j=2;j<i;j++)
if(i%j==0){
prime[i]=false;
break;
}
if(j==i) prime[i]=true;
}
}
int bfs(int first,int last){
bool dis[MAXV];
queue <int>q;
int v,i,j,temp,vtemp,count[MAXV],t[4];
memset(dis,false,sizeof(dis));
memset(count,0,sizeof(count));
q.push(first);
dis[first]=true;
while(!q.empty()){
v=q.front();
q.pop();
if(v==last) return count[v];
t[0]=v/1000;
t[1]=v%1000/100;
t[2]=v%100/10;
t[3]=v%10;
for(j=0;j<4;j++){
temp=t[j];//把第j位的数字先保存下来
for(i=0;i<10;i++)
if(i!=temp){
t[j]=i;
vtemp=t[0]*1000+t[1]*100+t[2]*10+t[3];
if(!dis[vtemp] && prime[vtemp]){
count[vtemp]=count[v]+1;
dis[vtemp]=true;
q.push(vtemp);
}
}
t[j]=temp;
}
}
return -1;
}
int main(){
int n,a,b,key;
init();
scanf("%d",&n);
while(n--){
scanf("%d%d",&a,&b);
key=bfs(a,b);
if(key!=-1) printf("%d\n",key);
else printf("Impossible\n");
}
return 0;
}