[kuangbin带你飞]专题一 简单搜索- F - Prime Path

#include <iostream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <map>
using namespace std;
#define INF 0x3f3f3f
int gcd(int a, int b) {return b==0 ? a:gcd(b,a%b);}

int a, b;
int flag;
int vis[10010];
int last_a[10010];
struct node
{
    int x;
    int step;
    node(){}
    node(int k1, int k2):x(k1),step(k2){}
};

int jud(int x)
{
    for(int i = 2; i <= sqrt(x); i++)
    {
        if(x%i==0) return 0;
    }
    return 1;
}

void bfs()
{
    memset(vis,0,sizeof(vis));
    queue<node>q;
    q.push((node){a,0});
    vis[a] = 1;
    while(!q.empty())
    {
        node p = q.front(); q.pop();
        if(p.x==b){
            flag = 1;
            printf("%d\n", p.step);
            break;
        }
        int x = p.x;
        int x1 = x/1000; int x2 = x/100%10; int x3 = x/10%10; int x4 = x%10;
        for(int i = 1; i < 10; i++)
        {
            if(i==x1) continue;
            int y = i*1000+x2*100+x3*10+x4;
            if(vis[y]||!jud(y)) continue;
            vis[y] = 1;
            q.push((node){y,p.step+1});
        }

        for(int i = 0; i < 10; i++)
        {
            if(i==x2) continue;
            int y = x1*1000+i*100+x3*10+x4;
            if(vis[y]||!jud(y)) continue;
            vis[y] = 1;
            q.push((node){y,p.step+1});
        }

        for(int i = 0; i < 10; i++)
        {
            if(i==x3) continue;
            int y = x1*1000+x2*100+i*10+x4;
            if(vis[y]||!jud(y)) continue;
            vis[y] = 1;
            q.push((node){y,p.step+1});
        }

        for(int i = 0; i < 10; i++)
        {
            if(i==x4) continue;
            int y = x1*1000+x2*100+x3*10+i;
            if(vis[y]||!jud(y)) continue;
            vis[y] = 1;
            q.push((node){y,p.step+1});
        }
    }
}

int main()
{
    int t;
    scanf("%d", &t);
    while(t--)
    {
        scanf("%d %d", &a, &b);
        flag = 0;
        bfs();
        if(!flag) printf("Impossible\n");
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值