package com;
import java.util.Scanner;
public class Main {
@SuppressWarnings("resource")
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Solution s = new Solution();
int T;
T = scan.nextInt();
while (T-- != 0) {
int m = scan.nextInt();
int n = scan.nextInt();
int[][] A = new int[m][n];
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; j++) {
A[i][j] = scan.nextInt();
}
int res = s.numEnclaves(A);
System.out.println(res);
}
}
}
class Solution {
public int[][] vis;
public int numEnclaves(int[][] A) {
int row = A.length, col = A[0].length;
vis = new int[row][col];
for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
if (i * j == 0 || i == row - 1 || j == col - 1) {
A[i][j] = 2;
vis[i][j] = 1;
dfs(i, j, A);
}
}
}
int res = 0;
for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
if (A[i][j] == 1)
++res;
}
}
return res;
}
private void dfs(int x, int y, int[][] A) {
// TODO Auto-generated method stub
if (x < 0 || y < 0 || x >= A.length || y >= A[0].length || A[x][y] != 1)
return;
A[x][y] = 2;
dfs(x + 1, y, A);
dfs(x - 1, y, A);
dfs(x, y + 1, A);
dfs(x, y - 1, A);
}
}
内部的1要想走出去,一定是一串1的路径
那么我们逆向思维,从边界的1向内部dfs,将经过的1感染为2
最后剩下的1就是被0包围1