#include<bits/stdc++.h>
using namespace std;
const int fx[8]={+1,+2,-1,-2,-2,-1,+1,+2};
const int fy[8]={+2,+1,+2,+1,-1,-2,-2,+1};
const int G[10][10]={
{0,0,0,0,0,0},
{0,1,1,1,1,1},
{0,0,1,1,1,1},
{0,0,0,-1,1,1},
{0,0,0,0,0,1},
{0,0,0,0,0,0},
};
int T,maxdeep;
int a[10][10];
bool f=0;
int check(){
int jsq=0;
for(int i=1;i<=5;i++){
for(int j=1;j<=5;j++)
if(a[i][j]!=G[i][j]) jsq++;
}
return jsq;
}
void ida(int t,int x,int y){
if(f==1) return ;
if(t>maxdeep){
if(check()==0) f=1;
return;
}
for(int k=0;k<8;k++){
int xx=x+fx[k],yy=y+fy[k];
if(xx<1||yy<1||xx>5||yy>5) continue;
swap(a[xx][yy],a[x][y]);
int tmp=check();
if(t+tmp<=maxdeep)ida(t+1,xx,yy);
swap(a[xx][yy],a[x][y]);
}
}
int main(){
cin>>T;
int sx,sy;
for(int p=1;p<=T;p++){
for(int i=1;i<=5;i++){
for(int j=1;j<=5;j++){
char c; cin>>c;
if(c=='*'){
a[i][j]=-1;
sx=i,sy=j;
}
else a[i][j]=c-'0';
}
}
if(check()==0){
cout<<0<<endl;
continue;
}
f=0;
for(maxdeep=1;maxdeep<=15;maxdeep++){
ida(1,sx,sy);
if(f==1){
cout<<maxdeep<<endl;
break;
}
}
if(f==0) cout<<-1<<endl;
}
return 0;
}