Prime Path
题意:t组输入,每组输入n,m,n和m都是四位数的,要求每次改变一个位置的数,要求改变之后的数仍是质数,问最少几步可以从n变成m。
思路:最短的,最少的,采用bfs,每次改变一个位置,个位只能是奇数,如果是偶数那肯定就不是质数了,千位不能为0,四个for循环,每一位的变化存入queue中,记得标记已经到达过的数。
代码
#include<cstdio>
#include<cstring>
#include<cmath>
#include<math.h>
#include<queue>
#include<algorithm>
using namespace std;
int n, m;
const int N = 1e4 + 100;
int vis[N];
struct E
{
int x,step;
} c,s,t;
queue<E>q;
int check(int x)
{
if(x<=1)
return 0;
else if(x==2||x==3)
return 1;
else
{
for(int i=2; i*i<=x; i++)
{
if(x%i==0)
return 0;
}
return 1;
}
}
void bfs()
{
while(!q.empty())
{
c=q.front();
q.pop();
if(c.x==m)
{
printf("%d\n",c.step);
return;
}
for(int i=1; i<=9; i+=2)
{
t.x=c.x/10*10+i;
if(!vis[t.x]&&check(t.x)&&t.x!=c.x)
{
vis[t.x]=1;
t.step=c.step+1;
q.push(t);
}
}
for(int i=0; i<=9; i++)
{
t.x=c.x/100*100+i*10+c.x%10;
if(!vis[t.x]&&check(t.x)&&t.x!=c.x)
{
vis[t.x]=1;
t.step=c.step+1;
q.push(t);
}
}
for(int i=0; i<=9; i++)
{
t.x=c.x/1000*1000+i*100+c.x%100;
if(!vis[t.x]&&check(t.x)&&t.x!=c.x)
{
vis[t.x]=1;
t.step=c.step+1;
q.push(t);
}
}
for(int i=1; i<=9; i++)
{
t.x=c.x%1000+i*1000;
if(!vis[t.x]&&check(t.x)&&t.x!=c.x)
{
vis[t.x]=1;
t.step=c.step+1;
q.push(t);
}
}
}
printf("Impossible\n");
return;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
while(!q.empty())
q.pop();
memset(vis,0,sizeof(vis));
s.x=n;
s.step=0;
vis[n]=1;
q.push(s);
bfs();
}
return 0;
}