#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 6;
char g[N][N], backup[N][N];
bool st[5];
int dx[5] = {-1, 0, 1, 0, 0}, dy[5] = {0, 1, 0, -1, 0};
void turn(int x, int y)
{
for (int i = 0; i < 5; i ++)
{
int a = x + dx[i], b = y + dy[i];
if (a < 0 || a >= 5 || b < 0 || b >= 5) continue;
g[a][b] ^= 1;
}
}
void dfs(int u, int &res)
{
if (u > 4) // 下标从0开始,0~4
{
memcpy(backup, g, sizeof g); // 记得备份
// 开始操作
int step = 0;
for (int i = 0; i < 5; i ++)
if (st[i])
step ++, turn(0, i);
for (int i = 0; i < 4; i ++)
for (int j = 0; j < 5; j ++)
{
if (g[i][j] == '0')
{
step ++;
turn(i + 1, j);
}
}
bool dark = false;
for (int i = 0; i < 5; i ++)
if (g[4][i] == '0')
{
dark = true;
break;
}
if (!dark) res = min(res, step);
memcpy(g, backup, sizeof g); // 恢复现场
return;
}
// 下面是枚举不同操作
// 选 or 不选
// 选
st[u] = true;
dfs(u + 1, res);
// 恢复现场
st[u] = false;
// 不选
st[u] = false;
dfs(u + 1, res);
// 恢复现场
st[u] = false;
}
int main()
{
int T;
scanf("%d", &T);
while (T --)
{
for (int i = 0; i < 5; i ++) scanf("%s", g[i]);
int res = 10;
dfs(0, res);
if (res > 6) res = -1;
cout << res << endl;
}
}