#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; #define xx first #define yy second #define pb push_back #define mp make_pair #define LL long long #define inf INT_MAX/3 #define mod 1000000007ll #define PI acos(-1.0) #define linf (1ll<<60)-1 #define FOR(I,A,B) for(int I = (A); I < (B); ++I) #define REP(I,N) FOR(I,0,N) #define ALL(A) ((A).begin(), (A).end()) #define set0(ar) memset(ar,0,sizeof ar) #define vsort(v) sort(v.begin(),v.end()) #define setinf(ar) memset(ar,126,sizeof ar) //cout << fixed << setprecision(20) << p << endl; template inline T bigmod(T p,T e,T M){ LL ret = 1; for(; e > 0; e >>= 1){ if(e & 1) ret = (ret * p) % M; p = (p * p) % M; } return (T)ret; } template inline T gcd(T a,T b){if(b==0)return a;return gcd(b,a%b);} template inline T modinverse(T a,T M){return bigmod(a,M-2,M);} int nxt[4][2] = { {-1, 0}, {0, -1}, {1, 0}, {0, 1} }; int pre[511*511], id[511][511]; pair < int, int > pp[500 * 501]; int Find(int x){ if(x == pre[x]) return x; return pre[x] = Find(pre[x]); } string ss[501]; int main() { // ios_base::sync_with_stdio(0); cin.tie(0); int T; cin >> T; while(T--){ int n, m; cin >> n >> m; int cnt = 1; FOR(i, 1, m+1) id[0][i] = 1; REP(i, n){ cin >> ss[i+1]; REP(j, m) id[i+1][j+1] = ++cnt; } cnt++; FOR(i, 1, m+1) id[n+1][i] = cnt; FOR(i, 1, cnt+1) pre[i] = i; int Q; cin >> Q; REP(i, Q){ cin >> pp[i+1].xx >> pp[i+1].yy; pp[i+1].xx++; pp[i+1].yy++; ss[pp[i+1].xx][pp[i+1].yy - 1] = '1'; } FOR(i, 1, n+1){ FOR(j, 1, m+1){ if(ss[i][j-1] == '1') continue; REP(k, 4){ int x = i + nxt[k][0], y = j + nxt[k][1]; if(y == 0 || y > m || (x > 0 && x <= n && ss[x][y-1] == '1')) continue; int px = Find(id[x][y]), py = Find(id[i][j]); if(px == py) continue; pre[px] = py; } } } if(Find(cnt) == Find(1)){ cout << -1 << endl; continue; } int fl = 0; for(int i = Q; i >= 1; i--){ ss[pp[i].xx][pp[i].yy - 1] = '0'; REP(k, 4){ int x = pp[i].xx + nxt[k][0], y = pp[i].yy + nxt[k][1]; if(y == 0 || y > m || (x > 0 && x <= n && ss[x][y-1] == '1')) continue; int px = Find(id[x][y]), py = Find(id[pp[i].xx][pp[i].yy]); if(px == py) continue; pre[px] = py; } if(Find(cnt) == Find(1)){ fl = i; break; } } cout << fl << endl; } }