#include<bits/stdc++.h>
using namespace std;
inline void swap(int &x,int &y){x^=y^=x^=y;}
const int tx[9]={0,1,1,-1,-1,2,2,-2,-2};
const int ty[9]={0,2,-2,2,-2,1,-1,1,-1};
const int base[6][6]={
{0,0,0,0,0,0},
{0,1,1,1,1,1},
{0,0,1,1,1,1},
{0,0,0,2,1,1},
{0,0,0,0,0,1},
{0,0,0,0,0,0}
};
int c[6][6];
int bx,by,nx,ny;
int success;
inline int evaluate()
{
int cnt=0;
for(int i=1;i<=5;i++)
for(int j=1;j<=5;j++)
if(c[i][j]!=base[i][j])
++cnt;
return cnt;
}
void A_star(int x,int y,int dep,int maxdep)
{
if(dep==maxdep)
{
if(!evaluate())
success=1;
return;
}
for(int i=1;i<=8;i++)
{
int nx=x+tx[i];
int ny=y+ty[i];
if(nx<1||nx>5||ny<1||ny>5)
continue;
swap(c[x][y],c[nx][ny]);
int sub=evaluate();
if(dep+sub<=maxdep)
A_star(nx,ny,dep+1,maxdep);
swap(c[x][y],c[nx][ny]);
}
}
signed main()
{
int t;
char x;
scanf("%d",&t);
while(t--)
{
success=0;
for(int i=1;i<=5;i++)
{
getchar();
for(int j=1;j<=5;j++)
{
scanf("%c",&x);
if(x=='*')
c[i][j]=2,bx=i,by=j;
else
c[i][j]=(x^48);
}
}
if(!evaluate())
{
puts("0");
continue;
}
for(int maxdep=1;maxdep<=15;maxdep++)
{
A_star(bx,by,0,maxdep);
if(success)
{
printf("%d\n",maxdep);
goto LEMON;
}
}
puts("-1");
LEMON:;
}
exit(0);
}