#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;
}
[kuangbin带你飞]专题一 简单搜索- F - Prime Path
最新推荐文章于 2023-03-03 16:06:53 发布