Prime Path(bfs)

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值