POJ - 3126 Prime Path 简单搜索

#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <map>
#include <cmath>
#include <queue>
using namespace std;
struct node
{
    int x,step;
}k,t;
bool is_prime(int n)
{
    if(n==1||n==0)return false;
    for(int i=2;i<=sqrt(n);i++)
        if(n%i==0)return false;
    return true;
}
bool vis[10005];
int main()
{
    int T;
    int a,b;
    scanf("%d",&T);
    while (T--)
    {
        scanf("%d%d",&a,&b);
        memset(vis,0,sizeof(vis));
        vis[a]=1;
        queue<node>q;
        k.x=a;
        k.step=0;
        q.push(k);
        while (!q.empty())
        {
            k=q.front();
            if(k.x==b)break;
            q.pop();
            int num=k.x;
            for(int i=0;i<10;i++)
            {
                int temp=num/10*10+i;
                if(is_prime(temp)&&vis[temp]==0)
                {
                    t.x=temp;
                    t.step=k.step+1;
                    q.push(t);
                    vis[temp]=1;
                }
            }
            for(int i=0;i<10;i++)
            {
                int temp=num/100*100+i*10+num%10;
                if(is_prime(temp)&&vis[temp]==0)
                {
                    t.x=temp;
                    t.step=k.step+1;
                    q.push(t);
                    vis[temp]=1;
                }
            }
            for(int i=0;i<10;i++)
            {
                int temp=(num/1000*1000)+i*100+num%100;
                if(is_prime(temp)&&vis[temp]==0)
                {
                    t.x=temp;
                    t.step=k.step+1;
                    q.push(t);
                    vis[temp]=1;
                }
            }
            for(int i=1;i<10;i++)
            {
                int temp=i*1000+num%1000;
                if(is_prime(temp)&&vis[temp]==0)
                {
                    t.x=temp;
                    t.step=k.step+1;
                    q.push(t);
                    vis[temp]=1;
                }
            }
        }
        if(q.empty())
        {
            printf("Impossible\n");
        }
        else cout<<k.step<<endl;
    }
    
    return 0;
}
发布了19 篇原创文章 · 获赞 19 · 访问量 682

猜你喜欢

转载自blog.csdn.net/qq_44086097/article/details/104148694