#include<cstdio>
#include<string>
#include<cstring>
#include<map>
using namespace std;
int T,ans;
int dp[8][25]={{-1,-1,-1,-1,-1, -1,-1,0,1,2, -1,-1,5,6,7 ,-1,-1,10,11,12 ,-1,-1,15,16,17},{-1,-1,-1,-1,-1, -1,-1,-1,-1,-1, -1,0,1,2,3, -1,5,6,7,8, -1,10,11,12,13},{-1,-1,-1,-1,-1, -1,-1,-1,-1,-1, 1,2,3,4,-1, 6,7,8,9,-1, 11,12,13,14,-1},{-1,-1,-1,-1,-1, 2,3,4,-1,-1, 7,8,9,-1,-1, 12,13,14,-1,-1, 17,18,19,-1,-1},{7,8,9,-1,-1, 12,13,14,-1,-1, 17,18,19,-1,-1, 22,23,24,-1,-1, -1,-1,-1,-1,-1},{11,12,13,14,-1, 16,17,18,19,-1, 21,22,23,24,-1, -1,-1,-1,-1,-1, -1,-1,-1,-1,-1},{-1,10,11,12,13, -1,15,16,17,18, -1,20,21,22,23, -1,-1,-1,-1,-1, -1,-1,-1,-1,-1},{-1,-1,5,6,7, -1,-1,10,11,12, -1,-1,15,16,17, -1,-1,20,21,22, -1,-1,-1,-1,-1}};
string End="111110111100*110000100000";
map<string,int>vist,D,H;
void init()
{
vist.clear();
D.clear();
H.clear();
ans=16;
}
void dfs(string s,int d,int h,int f,int p)
{
if(s==End)
{
ans=min(ans,d);
return;
}
if(f>=ans)
return;
d++;
for(int i=0;i<8;i++)
{
int p_=dp[i][p];
if(p_!=-1)
{
string s_=s;
s_[p]=s_[p_],s_[p_]='*';
if(!vist[s_])
{
vist[s_]=1;
int h_=h-(s[p]!=End[p])-(s[p_]!=End[p_])+(s_[p]!=End[p])+(s_[p_]!=End[p_]);
D[s_]=d,H[s_]=h_;
dfs(s_,d,h_,d+(h_*4/5),p_);
}
else if(d<D[s_])
{
D[s_]=d;
dfs(s_,d,H[s_],d+(H[s_]*4/5),p_);
}
}
}
}
int main()
{
scanf("%d",&T);
while(T--)
{
init();
string s;
s.resize(25);
for(int i=0;i<25;i+=5)
scanf("%s",&s[i]);
int h=0,f,p;
for(int i=0;i<25;i++)
{
if(s[i]!=End[i])
h++;
if(s[i]=='*')
p=i;
}
f=h*4/5;
vist[s]=1;
D[s]=0;
H[s]=h;
if(f<=15)
dfs(s,0,h,f,p);
printf(ans<16?"%d\n":"-1\n",ans);
}
return 0;
}