Problem: Time Limit: 8 sec / Memory Limit: 64 MB





Example

Input

10 10
.....#....
.....#....
.....#....
######....
..........
####......
....###...
t..#..####
...##.....
....#...##
3
0 3
0 5
4 6


Output

2

Solution (in CPP):

Solution:
#include<bits/stdc++.h>
using namespace std;
using Int = long long;
template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;}
template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;}


struct UnionFind{
  Int n;
  vector<Int> r,p;
  UnionFind(){}
  UnionFind(Int sz):n(sz),r(sz,1),p(sz,0){iota(p.begin(),p.end(),0);}
  Int find(Int x){
    return (x==p[x]?x:p[x]=find(p[x]));
  }
  bool same(Int x,Int y){
    return find(x)==find(y);
  }
  void unite(Int x,Int y){
    x=find(x);y=find(y);
    if(x==y) return;
    if(r[x]<r[y]) swap(x,y);
    r[x]+=r[y];
    p[y]=x;
  }
  Int size(Int x){
    return r[find(x)];
  }
};

//INSERT ABOVE HERE
signed main(){
  Int w,h;
  cin>>w>>h;

  vector<string> st(h);
  for(Int i=0;i<h;i++) cin>>st[i];

  auto idx=[&](Int y,Int x){return y*w+x;};  
  UnionFind uf(h*w);
  
  auto in=[&](Int y,Int x){return 0<=y&&y<h&&0<=x&&x<w;};
  Int dy[]={0,0,1,-1};
  Int dx[]={1,-1,0,0};

  auto check=
    [&](Int y,Int x)->void{
      if(!in(y,x)||st[y][x]=='#') return;
      for(Int k=0;k<4;k++){
        Int ny=y+dy[k],nx=x+dx[k];
        if(in(ny,nx)&&st[ny][nx]!='#')
          uf.unite(idx(y,x),idx(ny,nx));        
      }
    };

  for(Int i=0;i<h;i++)
    for(Int j=0;j<w;j++)
      check(i,j);
  
  Int ty=0,tx=0;
  for(Int i=0;i<h;i++)
    for(Int j=0;j<w;j++)
      if(st[i][j]=='t')
        ty=i,tx=j;  
  
  if(uf.same(idx(0,0),idx(ty,tx))){
    cout<<0<<endl;
    return 0;
  }

  Int n;
  cin>>n;
  
  Int x,y,cnt=0;
  while(cin>>x>>y){
    cnt++;
    if(st[y][x]!='#') continue;
    st[y][x]='.';
    check(y,x);
    if(uf.same(idx(0,0),idx(ty,tx))){
      cout<<cnt<<endl;
      return 0;
    }
  }
 
  cout<<-1<<endl;
  return 0;
}