#include #include #include #include #include #include #include #include #include #include #include #include #define SZ(X) ((int)(X).size()) #define ALL(X) (X).begin(), (X).end() #define REP(I, N) for (int I = 0; I < (N); ++I) #define REPP(I, A, B) for (int I = (A); I < (B); ++I) #define RI(X) scanf("%d", &(X)) #define RII(X, Y) scanf("%d%d", &(X), &(Y)) #define RIII(X, Y, Z) scanf("%d%d%d", &(X), &(Y), &(Z)) #define DRI(X) int (X); scanf("%d", &X) #define DRII(X, Y) int X, Y; scanf("%d%d", &X, &Y) #define DRIII(X, Y, Z) int X, Y, Z; scanf("%d%d%d", &X, &Y, &Z) #define RS(X) scanf("%s", (X)) #define CASET int ___T, case_n = 1; scanf("%d ", &___T); while (___T-- > 0) #define MP make_pair #define PB push_back #define MS0(X) memset((X), 0, sizeof((X))) #define MS1(X) memset((X), -1, sizeof((X))) #define LEN(X) strlen(X) #define PII pair #define VI vector #define VPII vector > #define PLL pair #define VPLL vector > #define F first #define S second typedef long long LL; using namespace std; const int MOD = 1e9+7; const int SIZE = 1e6+10; int N,M; char s[555][555]; int xx[SIZE],yy[SIZE]; struct Union_Find{ int d[SIZE],num[SIZE]; void init(int n){ REP(i,n)d[i]=i,num[i]=1; } int find(int x){ return (x!=d[x])?(d[x]=find(d[x])):x; } bool uu(int x,int y){ x=find(x); y=find(y); if(x==y)return 0; if(num[x]<=num[y]){ num[y]+=num[x]; d[x]=y; } else{ num[x]+=num[y]; d[y]=x; } return 1; } }U; int dx[4]={1,0,-1,0}; int dy[4]={0,1,0,-1}; bool Out(int x,int y){return x<0||y<0||x>=N||y>=M;} int get(int x,int y){return x*M+y;} int main(){ CASET{ RII(N,M); U.init(N*M+2); REP(i,N)RS(s[i]); DRI(Q); REP(i,Q){ RII(xx[i],yy[i]); s[xx[i]][yy[i]]='1'; } REP(i,N)REP(j,M){ if(s[i][j]=='1')continue; if(i+1=0;i--){ int x=xx[i],y=yy[i]; s[x][y]='0'; if(!x)U.uu(N*M,get(x,y)); if(x==N-1)U.uu(N*M+1,get(x,y)); REP(k,4){ int nx=x+dx[k]; int ny=y+dy[k]; if(Out(nx,ny))continue; if(s[nx][ny]=='1')continue; U.uu(get(nx,ny),get(x,y)); } if(U.find(N*M)==U.find(N*M+1)){ an=i+1; break; } } printf("%d\n",an); } } return 0; }