#include <bits/stdc++.h>
using namespace std;
#define rep(i,a,b) for(register int i = a;i <= b;++i)
int mp[10][10],x,y,t,now;
int ans[10][10] = {
{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 dx[10] = {0,-1,-2,-2,-1,1,2,2,1},dy[10] = {0,2,1,-1,-2,-2,-1,1,2},flag;
bool check(){
rep(i,1,5) rep(j,1,5) if(ans[i][j] != mp[i][j]) return false;return true;
} int rest(){
int ans1 = 0;rep(i,1,5) rep(j,1,5) ans1 += ans[i][j] != mp[i][j];return ans1;
} void dfs(int st,int ex,int ey){
//cout << now-st+1 << ' ' << ex << ' ' << ey << endl;
if(flag != -1) return;
if(st == 0) {if(check()) flag = now; return;}
if((now-st+1) + rest() > 16) return;
rep(i,1,8){
int sx = ex+dx[i],sy = ey+dy[i];
if(sx < 1||sx > 5||sy < 1||sy > 5) continue;
swap(mp[ex][ey],mp[sx][sy]);
dfs(st-1,sx,sy);
swap(mp[ex][ey],mp[sx][sy]);
}
return;
} int main(){
scanf("%d",&t);
while(t--){
flag = -1;
rep(i,1,5){
scanf("\n");
rep(j,1,5){
scanf("%c",&mp[i][j]);
if(mp[i][j] == '*')
mp[i][j] = 2,x = i,y = j;
else
mp[i][j] -= '0';
}
} for(now = 1;now <= 15;++now){
dfs(now,x,y);
if(flag != -1) break;
}
printf("%d\n",flag);
}
return 0;
}