#include<bits/stdc++.h>
using namespace std;
struct TI
{
int a[8][8];
}n;
int a[6][6]={
0,0,0,0,0,0,
0,2,2,2,2,2,
0,1,2,2,2,2,
0,1,1,0,2,2,
0,1,1,1,1,2,
0,1,1,1,1,1,
};
char c;
int x,y,T,k=15;
int dx[9]={0,-2,-2,-1,-1,1,1,2,2};
int dy[9]={0,-1,1,-2,2,-2,2,-1,1};
int pan;
void sou(TI n,int x,int y,int stepp,int xian)
{
int l=0;
for(int i=1;i<=5;++i){
for(int j=1;j<=5;++j){
if(n.a[i][j]!=a[i][j])l++;
}
}
if(pan||stepp+l>xian)return;
if(!l&&stepp<=k){pan=1;cout<<stepp<<endl;return;}
for (int i=1;i<=8;i++)
if (x+dx[i]>=1&&x+dx[i]<=5&&y+dy[i]>=1&&y+dy[i]<=5)
{
n.a[x][y]=n.a[x+dx[i]][y+dy[i]];
n.a[x+dx[i]][y+dy[i]]=0;
sou(n,x+dx[i],y+dy[i],stepp+1,xian);
n.a[x+dx[i]][y+dy[i]]=n.a[x][y];
n.a[x][y]=0;
}
}
int main()
{
cin>>T;
while(T--)
{
pan=0;
for(int i=1;i<=5;++i){
for(int j=1;j<=5;++j){
cin>>c;
if(c=='*'){x=i;y=j;n.a[i][j]=0;}
if(c=='1'){n.a[i][j]=2;}
if(c=='0'){n.a[i][j]=1;}
}
}
for(int i=1;i<=15;++i){
sou(n,x,y,0,i);
if(pan==1)break;
}
if(pan==0)cout<<"-1"<<endl;
}
return 0;
}