Here is a simple and easy approach using dfs with execution time is 0.01s.
#include <bits/stdc++.h>
using namespace std;
void dfs(vector < int > a[], int n, int m, int i, int j, int & p) {
if (i < 0 || i > n || j < 0 || j > m || a[i][j] == 0 || a[i][j] == -1)
return;
++p;
a[i][j] = -1;
dfs(a, n, m, i + 1, j, p);
dfs(a, n, m, i - 1, j, p);
dfs(a, n, m, i, j + 1, p);
dfs(a, n, m, i, j - 1, p);
dfs(a, n, m, i - 1, j - 1, p);
dfs(a, n, m, i - 1, j + 1, p);
dfs(a, n, m, i + 1, j - 1, p);
dfs(a, n, m, i + 1, j + 1, p);
}
int main() {
//code
int t;
cin >> t;
while (t--) {
int n, m, l;
cin >> n >> m;
// vector<vector<int> > v(n,vector<int>(m));
// for(int i=0;i<n;++i)
// {
// for(int j=0;j<m;++j)
// {
// cin>>l;
// v[i][j]=l;
// }
// }
vector < int > a[n];
int i, j;
for (i = 0; i < n; i++) {
vector < int > temp(m, 0);
a[i] = temp;
for (j = 0; j < m; j++)
cin >> a[i][j];
}
int ans = 0;
int p = 0;
for (i = 0; i < n; ++i)
for (j = 0; j < m; ++j)
if (a[i][j] == 1) {
p = 0;
dfs(a, n - 1, m - 1, i, j, p);
ans = max(ans, p);
}
cout << ans << endl;
}
return 0;
}