#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int N = 60;
int T;
int m,n;
char g[N][N];
bool st[N][N];
int dx[8] = {-1, -1, -1, 0, 1, 1, 1, 0}, dy[8] = {-1, 0, 1, 1, 1, 0, -1, -1};
int dx1[4] = {-1, 0, 1, 0}, dy1[4] = {0, 1, 0, -1};
void bfs_0(int x,int y){
queue<pair<int,int>> q,store;
q.push({x,y});store.push({x,y});
st[x][y] = true;
bool touch = false;
while(!q.empty()){
auto t = q.front();
q.pop();
for(int i=0;i<8;i++){
int tx = t.first + dx[i], ty = t.second + dy[i];
if(tx<1 || tx>m || ty<1 || ty>n || g[tx][ty]!='0' || st[tx][ty]) continue;
q.push({tx,ty});store.push({tx,ty});
st[tx][ty] = true;
if(tx == 1 || tx == m || ty == 1 || ty == n) touch = true;
}
}
if(!touch){
while(store.size()){
auto t = store.front();
store.pop();
int x = t.first, y = t.second;
g[x][y] = '1';
}
}
}
void bfs_1(int x,int y){
queue<pair<int,int>> q;
q.push({x,y});
st[x][y] = true;
while(!q.empty()){
auto t = q.front();
q.pop();
for(int i=0;i<4;i++){
int tx = t.first + dx1[i], ty = t.second + dy1[i];
if(tx<1 || tx>m || ty<1 || ty>n || g[tx][ty]!='1' || st[tx][ty]) continue;
q.push({tx,ty});
st[tx][ty] = true;
}
}
}
int main()
{
cin >> T;
while(T--){
cin >> m >> n;
for(int i=1;i<=m;i++){
for(int j=1;j<=n;j++){
cin >> g[i][j];
}
}
memset(st, 0, sizeof st);
for(int i=2;i<=m;i++){
for(int j=2;j<=n;j++){
if(g[i][j] == '0' && !st[i][j]){
bfs_0(i,j);
}
}
}
memset(st, 0, sizeof st);
int cnt = 0;
for(int i=1;i<=m;i++){
for(int j=1;j<=n;j++){
if(g[i][j]=='1' && !st[i][j]){
bfs_1(i,j);
cnt ++;
}
}
}
cout<<cnt<<endl;
}
return 0;
}