1973 Prime Path 广搜

#include<iostream>
#include<string>
#include<string.h>
#include<stdio.h>
#include<math.h>
#include<queue>
#include<algorithm>
using namespace std;
int prime[10000],b,ok;
int vis[10000];
struct node{
    int k;
    int step;
};
queue<node> q;
int bfs(){
    node temp,next;
    int x,y;
    while(!q.empty()){
        temp=q.front();
       // cout<<temp.k<<" "<<temp.step<<endl;
        q.pop();
        x=temp.k;
       //换个位
       y=x%10;
       for(int i=0;i<=9;i++){
        if(i!=y){
        int u=x/10*10+i;
         if(u==b) {ok=1;break;}
        if(prime[u]==1&&vis[u]==0){
             //    cout<<u<<"  个"<<endl;
           vis[u]=1;
            next.k=u;
            next.step=temp.step+1;
            q.push(next);
        }
       }
       }
       //换十位
       y=x%100/10;
       for(int i=0;i<=9;i++){
           if(i!=y){
        int u=x/100*100+i*10+x%10;
           if(u==b) {ok=1;break;}
        if(prime[u]&&vis[u]==0){
             //    cout<<u<<"  十"<<endl;
             vis[u]=1;
             next.k=u;
            next.step=temp.step+1;
            q.push(next);
         }
        }
       }


       //换百位
       y=x%1000/100;
       for(int i=0;i<=9;i++){
        if(i!=y){
            int u=x/1000*1000+i*100+x%100;
             if(u==b) {ok=1;break;}
            if(prime[u]&&vis[u]==0){
          //           cout<<u<<"  百"<<endl;
            vis[u]=1;
            next.k=u;
            next.step=temp.step+1;
            q.push(next);
            }
        }
       }
       //换千位
       y=x/1000;
       for(int i=1;i<=9;i++){
        if(i!=y){
           int u=i*1000+x%1000;

            if(u==b) {ok=1;break;}
            if(prime[u]&&vis[u]==0){
          //  cout<<u<<"  千"<<endl;
             vis[u]=1;
            next.k=u;
            next.step=temp.step+1;
            q.push(next);
            }
        }
       }

       if(ok) {break;}
    }
    return temp.step+1;
}
int main(){
    int t,a,ff;
    memset(prime,0,sizeof(prime));

    for(int i=1000;i<10000;i++){
        double r=sqrt(i);
        ff=0;
        for(int j=2;j<=r;j++){
            if(i%j==0) {ff=1;break;}
        }
        if(ff==0) {prime[i]=1;}
    }
    cin>>t;
    while(t--){
        cin>>a>>b;
        if(a==b){cout<<0<<endl;continue;}
        while(!q.empty()) q.pop();
        ok=0;
    memset(vis,0,sizeof(vis));
       node a1;
       a1.k=a;
       a1.step=0;
       q.push(a1);
       vis[a]=1;
       int uu=bfs();
       cout<<uu<<endl;
    }



    return 0;
}

 

posted @ 2016-02-29 19:41  咸咸的告别  阅读(250)  评论(0编辑  收藏  举报