#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
char st[6][6], backup[6][6];
int dx[5] = {0, 0, 1, 0, -1}, dy[5] = {0, -1, 0, 1, 0};
int n, steps, ans;
bool is_ok;
void turn(int x, int y)
{
int x1, y1;
for (int i = 0; i < 5; i++)
{
x1 = x + dx[i], y1 = y + dy[i];
if (x1 < 0 || x1 > 4 || y1 < 0 || y1 > 4)
continue;
st[x1][y1] ^= 1;
}
}
int main()
{
cin >> n;
while (n--)
{
for (int i = 0; i < 5; i++)
cin >> st[i];
memcpy(backup, st, sizeof st);
ans = 99;
for (int op = 0; op < 32; op++) // 遍历所有情况,第一行有32种情况
{
steps = 0;
is_ok = true;
memcpy(st, backup, sizeof backup);
for (int j = 0; j < 5; j++)
if (op >> j & 1)
{
turn(0, 4 - j);
steps++;
}
for (int j = 0; j <= 3; j++) // 按照上行进行开关灯
{
for (int k = 0; k < 5; k++)
if (st[j][k] == '0')
{
steps++;
turn(j + 1, k);
}
}
for (int j = 0; j <= 4; j++) // 最后判断是否ok
if (st[4][j] == '0')
{
is_ok = false;
break;
}
if (is_ok) ans = min(steps, ans);
}
if (ans <= 6) printf("%d\n", ans);
else printf("-1\n");
}
return 0;
}