题意:给两个素数a,b,求将a变成b的最小次数,一次只能变一位而且每次变化后的数字必须是素数。
题解:bfs
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <string>
#include <map>
#include <cstring>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#define ll long long
#define INF 0x3f3f3f3f
using namespace std;
bool vis[10000];
int n,m;
struct node{
int x;
int step;
};
int judge(int x){
if(x==1)return 0;
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;
node a;
a.step = 0;
a.x = n;
vis[a.x] = true;
q.push(a);
while(!q.empty()){
node now = q.front();
q.pop();
if(now.x==m){
cout<<now.step<<endl;
return;
}
for(int j = 1 ; j <= 4 ; j++){
if(j==1){
for(int i = 1 ; i <= 9 ; i+=2){
node next = now;
next.x = next.x/10*10+i;
if(next.x!=now.x&&!vis[next.x]&&judge(next.x)){
vis[next.x] = true;
next.step++;
q.push(next);
}
}
}else if(j==2){
for(int i = 0 ; i <= 9 ; i++){
node next = now;
next.x = next.x/100*100+i*10+now.x%10;
if(next.x!=now.x&&!vis[next.x]&&judge(next.x)){
vis[next.x] = true;
next.step++;
q.push(next);
}
}
}else if(j==3){
for(int i = 0 ; i <= 9 ; i++){
node next = now;
next.x = next.x/1000*1000+i*100+now.x%100;
if(next.x!=now.x&&!vis[next.x]&&judge(next.x)){
vis[next.x] = true;
next.step++;
q.push(next);
}
}
}else{
for(int i = 1 ; i <= 9 ; i++){
node next = now;
next.x = i*1000+now.x%1000;
if(next.x!=now.x&&!vis[next.x]&&judge(next.x)){
vis[next.x] = true;
next.step++;
q.push(next);
}
}
}
}
}
cout<<"Impossible"<<endl;
}
int main(){
int t;
cin>>t;
while(t--){
scanf("%d %d",&n,&m);
bfs();
}
}