#include <bits/stdc++.h>
using namespace std;
const int N = 50;
int n, m;
char g[N][N + 1];
int main(int argc, char **argv) {
int t;
scanf("%d", &t);
while (t-- != 0) {
scanf("%d%d", &n, &m);
for (int i = 0; i < n; ++i)
scanf("%s", g[i]);
int all = 0, ok = 0;
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j)
if (g[i][j] == '1') {
++all;
if (i == 0 || j == 0 || i == n - 1 || j == m - 1)
++ok;
}
int need = n * 2 + m * 2 - 4;
if (all >= need)
printf("%d\n", need - ok);
else
puts("-1");
}
return 0;
}
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7Cgpjb25zdCBpbnQgTiA9IDUwOwppbnQgbiwgbTsKY2hhciBnW05dW04gKyAxXTsKCmludCBtYWluKGludCBhcmdjLCBjaGFyICoqYXJndikgewoJaW50IHQ7CglzY2FuZigiJWQiLCAmdCk7Cgl3aGlsZSAodC0tICE9IDApIHsKCQlzY2FuZigiJWQlZCIsICZuLCAmbSk7CgkJZm9yIChpbnQgaSA9IDA7IGkgPCBuOyArK2kpCgkJCXNjYW5mKCIlcyIsIGdbaV0pOwoJCWludCBhbGwgPSAwLCBvayA9IDA7CgkJZm9yIChpbnQgaSA9IDA7IGkgPCBuOyArK2kpCgkJCWZvciAoaW50IGogPSAwOyBqIDwgbTsgKytqKQoJCQkJaWYgKGdbaV1bal0gPT0gJzEnKSB7CgkJCQkJKythbGw7CgkJCQkJaWYgKGkgPT0gMCB8fCBqID09IDAgfHwgaSA9PSBuIC0gMSB8fCBqID09IG0gLSAxKQoJCQkJCQkrK29rOwoJCQkJfQoJCWludCBuZWVkID0gbiAqIDIgKyBtICogMiAtIDQ7CgkJaWYgKGFsbCA+PSBuZWVkKQoJCQlwcmludGYoIiVkXG4iLCBuZWVkIC0gb2spOwoJCWVsc2UKCQkJcHV0cygiLTEiKTsKCX0KCXJldHVybiAwOwp9