# POJ - 3126 - Prime Path 【BFS + 素数打表】

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<cmath>
#define INF 0x7ffffff
using namespace std;
const int maxn = 1e4+5;
bool prime[maxn];
int T, s, e;
void is_prime()
{
memset(prime, 1, sizeof(prime));
int m = sqrt(maxn);
prime[0] = prime[1] = false;
for (int i = 2; i < m; i++)
{
if(prime[i])
{
for (int j = i * i; j < maxn; j += i)
{
prime[j] = false;
}
}
}
}
bool Judge(int a, int b)
{
int cnt = 0;
if(a%10 != b%10) cnt++;
if(a%100/10 != b%100/10) cnt++;
if(a%1000/100 != b%1000/100) cnt++;
if(a/1000 != b/1000) cnt++;
if(cnt == 1) return true;
return false;
}
int bfs()
{
bool vis[10000];
memset(vis, 0, sizeof(vis));
pair<int, int> Now;
Now.first = s, Now.second = 0;
queue<pair<int, int> > q;
vis[s] = true;
q.push(Now);
while(!q.empty())
{
Now = q.front();
if(Now.first == e)
{
return Now.second;
}
q.pop();
for (int i = 1000; i < 10000; i++)
{
if(prime[i] && !vis[i] && Judge(i, Now.first))
{
vis[i] = true;
q.push(make_pair(i, Now.second + 1));
}
}
}
return -1;
}
int main()
{
is_prime();
scanf("%d", &T);
while(T--)
{
scanf("%d%d", &s, &e);
int ans = bfs();
if(ans != -1)
printf("%d\n",ans);
else
printf("Impossible\n");
}
}