#include <iostream>
#include <cstring>
#include <queue>
#define x first
#define y second
using namespace std;
using PII = pair <int, int>;
const int N = 60;
char ch;
int t, n, m, cnt, g[N][N], st[N][N];
PII dir8[8] = {
{-1, 0}, {-1, 1}, {0, 1}, {1, 1},
{1, 0}, {1, -1}, {0, -1}, {-1, -1}
};
PII dir4[4] = {
{0, 1}, {0, -1}, {1, 0}, {-1, 0}
};
void show(int g[N][N]) {
cout << '\n';
for(int i = 1; i <= n; ++i) {
for(int j = 1; j <= m; ++j) cout << g[i][j];
cout << '\n';
}
}
void bfs8(int x, int y) {
queue <PII> que;
que.push({x, y});
st[x][y] = 1;
while(!que.empty()) {
auto t = que.front(); que.pop();
for(int k = 0; k < 8; ++k) {
int I = t.x + dir8[k].x, J = t.y + dir8[k].y;
if(I >= 0 && I <= n + 1 && J >= 0 && J <= m + 1 && !g[I][J] && !st[I][J]) {
st[I][J] = 1;
que.push({I, J});
}
}
}
}
void bfs4(int x, int y) {
queue <PII> que;
que.push({x, y});
st[x][y] = 1;
while(!que.empty()) {
auto t = que.front(); que.pop();
for(int k = 0; k < 4; ++k) {
int I = t.x + dir4[k].x, J = t.y + dir4[k].y;
if(I >= 1 && I <= n && J >= 1 && J <= m && !st[I][J]) {
que.push({I, J});
st[I][J] = 1;
}
}
}
}
void solve() {
cnt = 0;
cin >> n >> m;
memset(g, 0, sizeof g);
memset(st, 0, sizeof st);
for(int i = 1; i <= n; ++i) {
for(int j = 1; j <= m; ++j) {
cin >> ch;
g[i][j] = (ch == '1');
}
}
bfs8(0,0);
for(int i = 1; i <= n; ++i) {
for(int j = 1; j <= m; ++j) {
if(g[i][j] && !st[i][j]) {
++cnt;
bfs4(i, j);
}
}
}
cout << cnt << '\n';
}
int main () {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> t;
while(t--) {
solve();
}
return 0;
}