思路:宽度优先搜索(BFS算法)

#include<iostream>
#include<stdio.h>
#include<cmath>
#include<cstring>
using namespace std;
int a,b;
struct node{
int num;
int step;
};
node que[10000];//默认初始化为0
int visit[10000];//默认初始化为0
int prime(int d){
if(d<=1) return 0;
for(int i=2;i<=sqrt(double(d));i++)
if(d%i==0) return 0;
return 1;
}
void bfs(){
int i;
int p1,p2;
p1=0;
que[p1].num=a;
que[p1].step=0;
visit[a]=1;
p2=1;
if(a==b){//考虑 a , b 相等的时候
printf("%d\n",0);
return ;
}
while(p1<p2){
node x=que[p1];
p1++; int unit=x.num%10;//取出个位
int decade=(x.num/10)%10;//取出十位
for(i=1;i<=9;i=i+2){ //枚举个位,保证为奇数(偶数必定不是素数)
int y=(x.num/10)*10+i;
if(y==b) { //如果找到了,直接退出
printf("%d\n",x.step+1);
return ;
}
if(visit[y]==0 &&prime(y)) {
visit[y]=true;
que[p2].num=y;
que[p2].step=x.step+1;
p2++;
}
}
for(i=0;i<=9;i++){ //枚举十位
int y=(x.num/100)*100+i*10+unit;
if(y==b) { //如果找到了,直接退出
printf("%d\n",x.step+1);
return ;
}
if(visit[y]==0 &&prime(y)) {
visit[y]=true;
que[p2].num=y;
que[p2].step=x.step+1;
p2++;
}
}
for(i=0;i<=9;i++){ //枚举百位
int y=(x.num/1000)*1000+i*100+decade*10+unit;
if(y==b) { //如果找到了,直接退出
printf("%d\n",x.step+1);
return ;
}
if(visit[y]==0 &&prime(y)){
visit[y]=true;
que[p2].num=y;
que[p2].step=x.step+1;
p2++;
}
}
for(i=1;i<=9;i++) {//枚举千位,保证千位不为0
int y=i*1000+x.num%1000;
if(y==b) { //如果找到了,直接退出
printf("%d\n",x.step+1);
return ;
}
if(visit[y]==0 &&prime(y)) {
visit[y]=true;
que[p2].num=y;
que[p2].step=x.step+1;
p2++;
}
}
}
printf("Impossible\n");
return;
}
int main(){
int n;
scanf("%d",&n);
while(n--) {
memset(visit,0,sizeof(visit));//不要忘记初始化
scanf("%d%d",&a,&b);
bfs();
}
return 0;
}

下面代码优化了一下判断素数的代码

int prime(int d){
if(d==2) return 1;//特殊情况,偶数2是素数
if( d<=1 || d%2==0 ) return 0;//排除d<=1时以及d为偶数时
for(int i=3;i<=sqrt(double(d));i=i+2)
if(d%i==0) return 0;
return 1;
}

最新文章

  1. httpd配置.md
  2. iOS 10 消息推送(UserNotifications)秘籍总结(二)
  3. openjudge 大师兄,师傅被妖怪抓走啦
  4. centos 编译swoole
  5. ps闪闪发光的字 教程+自我练习
  6. 《cut命令》-linux命令五分钟系列之十九
  7. cf Ping-Pong (Easy Version)
  8. 使用WCF扩展在方法调用前初始化环境
  9. Docker镜像的构成__docker commit
  10. 【Matlab编程】Matlab高效编程技巧
  11. socket通信如何处理每次包长度不定问题
  12. [日常] nginx记录post数据
  13. Python学习第二篇
  14. MySql数据库学习笔记(2)
  15. python学习-判断是否是IP地址
  16. Qt+QGis二次开发:创建临时图层并添加要素
  17. [转]windows环境下使用virtualenv对python进行多版本隔离
  18. bbs项目富文本编辑器实现上传文件到media目录
  19. Windows下使用Git Bash上传项目到GitHub
  20. Python多进程编程(转)

热门文章

  1. EJB是什么?(节选)
  2. Elasticsearch5.X IN Windows 10 系列文章(1)
  3. 要胀爆的Angular1.0
  4. ios -富文本和尺寸
  5. 微信小程序事件
  6. Configure the modules to be find by modprobe
  7. Entity Framework(1)——Connections and Models
  8. jquery 通过属性选择器获取input不为disabled的对象
  9. c# 怎么更改DataTable 中某列的值?
  10. 【python】-- web开发之HTML