bfs--POJ 3126 Prime Path

46 篇文章 0 订阅


思路: 搜索位上的数字 可以构成素数
#include <iostream>
#include <stdio.h>
#include <queue>
#include <cstring>
using namespace std;
int n, m;
int prime[10000];
void init()
{   int i,j;
    for( i=1000;i<=9999;i++)
    {
        for(j=2;j<=i/2;j++)
            if(i%j==0)
            break;
        if(j==i/2+1)
            prime[i]=1;
    }
}


const int N = 10010;
int vis[N];


struct node
{
    int x, step;
};
queue<node > Q;
void bfs()
{
    int x,stp,i;
    while(!Q.empty())
    {
        node tmp;
        tmp=Q.front();
        Q.pop();
        x=tmp.x;
        stp=tmp.step;
        if(x==m)
        {
            printf("%d\n",stp);
            return ;
        }
        for(int i=1;i<=9;i+=2)
        {
            int tep=x/10*10+i;
            if((!vis[tep])&&(tep!=x)&&(prime[tep]))
            {
                vis[tep]=1;
                node temp;
                temp.x=tep;
                temp.step=stp+1;
                Q.push(temp);
            }
        }
        for(int i=0;i<=9;i++)
        {
            int tep=x/100*100+i*10+x%10;
            if(!vis[tep]&&tep!=x&&prime[tep])
            {
                vis[tep]=1;
                node temp;
                temp.x=tep;
                temp.step=stp+1;


                Q.push(temp);
            }
        }
        for(int i=0;i<=9;i++)
        {
            int tep=x/1000*1000+i*100+x%100;
            if(!vis[tep]&&tep!=x&&prime[tep])
            {
                vis[tep]=1;
                node temp;
                temp.x=tep;
                temp.step=stp+1;
                Q.push(temp);
            }
        }
        for(int i=1;i<=9;i++)
        {
            int tep=i*1000+x%1000;
            if(!vis[tep]&&tep!=x&&prime[tep])
            {
                vis[tep]=1;
                node temp;
                temp.x=tep;
                temp.step=stp+1;
                Q.push(temp);
            }
        }


    }
    printf("Impossible\n");
    return ;
}
int main()
{
    int t;
    cin>>t;
    init();
    while(t--)
    {   while(!Q.empty())
        Q.pop();
        memset(vis,0,sizeof(vis));
        cin>>n>>m;
        vis[n]=1;
        node tmp;
        tmp.x=n;
        tmp.step=0;
        Q.push(tmp);
        bfs();
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值