#include<iostream>
using namespace std;
int map[6][6],ok;
int dx[9]={0,1,1,-1,-1,2,2,-2,-2},dy[9]={0,2,-2,2,-2,1,-1,1,-1};
int goal[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 f(){
int k=0;
for(int i=1;i<=5;i++){
for(int j=1;j<=5;j++)
if(map[i][j]!=goal[i][j]) k++;
}
return k;
}
void dfs(int x,int y,int k,int depth,int pre){
if(k==depth){
if(!f()) ok=1;
return;
}
for(int i=1;i<=8;i++){
int xx=x+dx[k],yy=y+dy[k];
if(xx>5||yy>5||xx<=0||yy<=0||pre+i==9) continue;
swap(map[xx][yy],map[x][y]);
if(k+f()-1<=depth) dfs(xx,yy,k+1,depth,i);
swap(map[xx][yy],map[x][y]);
}
}
void solve(){
ok=0;
char c;
int x,y;
for(int i=1;i<=5;i++){
for(int j=1;j<=5;j++){
cin>>c;
if(c!='*') map[i][j]=c-'0';
else map[i][j]=2,x=i,y=j;
}
}
for(int depth=1;depth<=15;depth++){
dfs(x,y,0,depth,-1);
if(ok){cout<<depth<<endl;return;}
}
cout<<-1<<endl;
}
int main(){
int T;cin>>T;
while(T--) solve();
return 0;
}