一道BFS题目
题意大致如下:
给定两个四位数 x ,y(x ,y都是素数)。要求从x变化到y。
变化规则为每次只能改变四位数x中的其中一位得到k,要求k也是素数。在这样的变化规则下求x变化到y的最小次数。
根据规则直接BFS就行。
代码如下:
#include <stdio.h>
#include <queue>
#include <iostream>
#include <cstring>
#include <math.h>
using namespace std;
int m,n;
int vis[10000];
struct node
{
int prime;
int step;
};
int a[20000];
int flag[20000];//给10000以内的所有素数打表
void isPrime()
{
memset (flag,0,sizeof(flag));
for(int i=2; i<10000; i++)
{
if(flag[i])
{
continue ;
}
else
{
for(int j=i+i; j<10000; j+=i)
{
flag[j]=1;
}
}
}
}
void bfs()
{
queue <node> que;
node x;
x.prime=m;
x.step=0;
vis[x.prime]=1;
que.push(x);
while(!que.empty())
{
node fx;
fx=que.front();
que.pop();
if(fx.prime==n)
{
cout<<fx.step<<endl;
break;
}
int po=1;
for(int i=1; i<=4; i++)
{
po*=10;
int k=fx.prime;
int s=fx.prime%po;
k=k-s+fx.prime%(po/10);
//k为改变一位数之后的最小的数字,例如1033改变十位上的数字则k=1003,改变千位则k=33;
for(int j=0; j<=9; j++)
{
if(i==4&&j==0)<span style="white-space:pre"> </span>//千位进行特判 因为千位不能为0 所以直接从1000开始加。其他的从0开始
continue;
int y=k+j*pow(10,i-1);
if(y==fx.prime)
continue;
if(!vis[y]&&!flag[y]&&y<10000)
{
vis[y]=1;
node fy;
fy.prime=y;
fy.step=fx.step+1;
que.push(fy);
}
}
}
}
return;
}
int main()
{
int t;
isPrime();
cin>>t;
while(t--)
{
memset(vis,0,sizeof(vis));
cin>>m>>n;
bfs();
}
return 0;
}