#include<bits/stdc++.h>
//#define int long long
using namespace std;
int target[6][6]={
{0,1,1,1,1,1},
{0,0,1,1,1,1},
{0,0,0,9,1,1},
{0,0,0,0,0,1},
{0,0,0,0,0,0},
};
int T;
int a[6][6];
int dx[8]={-2,-1,1,2,2,1,-1,-2};
int dy[8]={1,2,2,1,-1,-2,-2,-1};
int f(){
int cnt=0;
for(int i=1;i<=5;i++){
for(int j=1;j<=5;j++){
if(a[i][j]!=target[i][j]) cnt++;
}
}
return cnt;
}
bool dfs(int step,int now,bool flag){
if(now==step){
if(f()==0) return true;
return false;
}
int x,y;
for(int i=1;i<=5;i++){
for(int j=1;j<=5;j++){
if(a[i][j]==9){
x=i;
y=j;
break;
}
}
}
// cout<<x<<" "<<y<<"\n";
for(int i=0;i<8;i++){
int xx=x+dx[i];
int yy=y+dy[i];
if(xx<1 || yy<1 || xx>5 || yy>5) continue;
swap(a[x][y],a[xx][yy]);
if(f()+now<=step)
flag=dfs(step,now+1,flag);
if(flag) break;
swap(a[x][y],a[xx][yy]);
}
return flag;
}
void solve(){
for(int i=1;i<=5;i++){
for(int j=1;j<=5;j++){
char x;
cin>>x;
if(x=='*') a[i][j]=9;
else a[i][j]=x-'0';
}
}
int deep=0;
while(deep<=15 && !dfs(deep,0,false)) deep++;
if(deep>15) cout<<"-1\n";
else cout<<deep<<"\n";
return ;
}
signed main(){
cin>>T;
while(T--){
solve();
}
return 0;
}
舅舅我吧