#include #include #include #define num(i,j) (i-1)*m+j #define N 505 using namespace std; const int dx[10]={0,1,1,-1,-1,1,-1},dy[10]={0,1,-1,1,-1,0,0,1,-1}; int a[N][N],b[N][N],fa[N*N],T,n,m,x,y,q,ans; char s[N]; struct he{ int l,r; }data[N*N]; int gf(int x){ if(x==fa[x]) return x;return fa[x]=gf(fa[x]); } void init(){ memset(fa,0,sizeof(fa)); memset(a,0,sizeof(a)); memset(b,0,sizeof(b)); memset(data,0,sizeof(data)); } int main(){ scanf("%d",&T); while(T--){ init(); scanf("%d%d",&n,&m); for(int i=1;i<=n;i++) { scanf("%s",s); for(int j=1;j<=m;j++){ if(s[j-1]=='1') a[i][j]=1; fa[num(i,j)]=num(i,j); data[num(i,j)].l=data[num(i,j)].r=j; } } ans=-1; for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) if(a[i][j]){ b[i][j]=1; for(int o=1;o<=8;o++){ int x1=i+dx[o]; int y1=j+dy[o]; if(x1<1||y1<1||x1>n||y1>m||!a[x1][y1]||!b[i][j]) continue; int u=gf(num(i,j)),v=gf(num(x1,y1)); if(u!=v){ fa[u]=v; data[v].l=min(data[u].l,data[v].l); data[v].r=max(data[v].r,data[u].r); if(data[v].l==1&&data[v].r==m) ans=0; } } } scanf("%d",&q); for(int i=1;i<=q;i++){ scanf("%d%d",&x,&y); x++;y++; a[x][y]=1; for(int o=1;o<=8;o++){ int x1=x+dx[o]; int y1=y+dy[o]; if(x1<1||y1<1||x1>n||y1>m||!a[x1][y1]) continue; int u=gf(num(x,y)),v=gf(num(x1,y1)); if(u!=v){ fa[u]=v; data[v].l=min(data[u].l,data[v].l); data[v].r=max(data[v].r,data[u].r); if(data[v].l==1&&data[v].r==m&&ans==-1) ans=i; } } } printf("%d\n",ans); } }