/***************************************************************** Author:lbn187, a konjac TwT Date:2016-3-26 Contest:Codeforces Algorithm:QAQ ^_^ Orz hzh, NOI gold members, IOI 2016 world champion ^=^ Orz hhw, you are our blue moon, with you will live ^~^ Orz mxh, you are our red sun, without you we'll die ^-^ Orz yizhou, I wish you a successful marriage ^w^ Orz xianyangyu, you can sleep all the time in the game *****************************************************************/ #pragma comment(linker, "/STACK:102400000,102400000") #include #include #include #include #include #include #include #include #define sf scanf #define pf printf #define fo(i,n) for(int i=0;i=0;i--) #define rep(i,a,n) for(int i=a;i<=n;i++) #define per(i,a,n) for(int i=n;i>=a;i--) #define mjj(i,x) for(int i=fir[x];i;i=ne[i]) #define X first #define Y second #define Max(a,b) a=max(a,b) #define Min(a,b) a=min(a,b) #define mp make_pair #define rlr son[son[root][1]][0] #define gi(a) sf("%d",&a); #define gi2(a,b) sf("%d%d",&a,&b); #define gi3(a,b,c) sf("%d%d%d",&a,&b,&c); #define gl(a) sf("%I64d",&a); #define gs(s) sf("%s",s); #define pi(a) pf("%d\n",a); #define pi2(a,b) pf("%d %d\n",a,b); #define pl(a) pf("%I64d\n",a); #define spr(x) (x*x) #define pie acos(-1) #define CM(a,b) memcpy(a,b,sizeof(b)) #define CL(a) memset(a,0,sizeof(a)) #define N 252222 #define M 1000000007 #define inf 1e9 #define eps 1e-8 using namespace std; typedef long long LL;typedef unsigned long long ULL;typedef double LF;typedef long double LD; typedef pairpii;typedef pairpil;typedef pairpli;typedef pairpll;typedef pairpff; const int xx[]={1,-1,0,0},yy[]={0,0,1,-1};LL pow(LL a,LL b,LL p){LL sum=1;for(a%=p;b;a=a*a%p,b>>=1)if(b&1)sum=sum*a%p;return sum;} char ch;void rd(int &x){for(ch=getchar();ch<'0';ch=getchar());for(x=0;ch>='0';ch=getchar())x=x*10+ch-'0';} LL phi(LL n){LL i,re=n;for(i=2;i*i<=n;i++)if(n%i==0){re=re/i*(i-1);while(n%i==0)n/=i;}if(n>1)re=re/n*(n-1);return re%M;} void exgcd(LL a,LL b,LL &x,LL &y){if(!b){x=1;y=0;return;}exgcd(b,a%b,y,x);y-=x*(a/b);} LL gcd(LL a,LL b){return b==0?a:gcd(b,a%b);} int Q,n,m,x,y,i,j,tot,cnt,S,T,a[N],F[N];bool v[550][550];char s[550];LL A,B,C,ans; struct P{int x,y;}q[N]; int G(int x,int y){return x*m-m+y;} int gf(int x){return F[x]==x?x:F[x]=gf(F[x]);} void uni(int x,int y){F[gf(x)]=gf(y);} int main(){ int W; for(scanf("%d",&W);W--;){ scanf("%d%d",&n,&m);CL(v); for(i=1;i<=n;i++){ scanf("%s",s+1); for(j=1;j<=m;j++)if(s[j]=='1')v[i][j]=1; } for(i=1;i<=n*m+2;i++)F[i]=i;S=n*m+1;T=S+1; for(scanf("%d",&Q),i=1;i<=Q;i++)scanf("%d%d",&q[i].x,&q[i].y),q[i].x++,q[i].y++,v[q[i].x][q[i].y]=1; for(i=1;i<=n;i++)for(j=1;j<=m;j++)if(!v[i][j]){ if(i>1&&!v[i-1][j])uni(G(i-1,j),G(i,j)); if(j>1&&!v[i][j-1])uni(G(i,j-1),G(i,j)); } for(i=1;i<=m;i++)if(!v[1][i])uni(G(1,i),S); for(i=1;i<=m;i++)if(!v[n][i])uni(G(n,i),T); if(gf(S)==gf(T)){puts("-1");continue;} for(i=Q;i;i--){ x=q[i].x;y=q[i].y;v[x][y]=0; if(x>1&&!v[x-1][y])uni(G(x-1,y),G(x,y)); if(y>1&&!v[x][y-1])uni(G(x,y-1),G(x,y)); if(x