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 <stdio.h>
#include <math.h>

#include <bitset>
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <cstring>
#include <string>
#include <sstream>
#include <algorithm>
#include <iomanip>
#include <iostream>

#define VARIABLE(x) cerr << #x << "=" << x << endl
#define BINARY(x) cerr << #x << "=" << static_cast<bitset<16> >(x) << endl;
#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define REP(i,m,n) for (int i=m;i<(int)(n);i++)
#define if_range(x, y, w, h) if (0<=(int)(x) && (int)(x)<(int)(w) && 0<=(int)(y) && (int)(y)<(int)(h))

const int INF = 10000000;
int dx[4]={-1, 0, 1, 0}, dy[4]={0, -1, 0, 1};
using namespace std;
typedef pair<int, int> P;

/** Problem2364 : Lucky Dip **/
int field[1000][1000];
int d[1000][1000];
const int GOAL = 10000;
int W, H, N;


bool search(int n)
{
	fill(d[0], d[0]+1000*1000, INF);
	
	queue<P> Q;
	Q.push(P(0,0));
	d[0][0] = 1;
	
	while (Q.size()) {
		P p = Q.front(); Q.pop();
		
		rep(i, 4) {
			int nx=p.first+dx[i], ny=p.second+dy[i];
			if_range(nx, ny, W, H) {
				if (field[nx][ny]==GOAL)
					return true;
				
				if (field[nx][ny] <= n && d[nx][ny]==INF) {
					Q.push(P(nx, ny));
					d[nx][ny]=d[p.first][p.second]+1;
				}
			}
		}
	}
	
	return false;
}

int main()
{
	cin>>W>>H;
	rep(y, H) {
		rep(x, W) {
			char c;
			cin>>c;
			if (c=='.')
				field[x][y]=0;
			else if (c=='#')
				field[x][y]=INF;
			else if (c=='t')
				field[x][y]=GOAL;
		}
	}
	
	if (search(0)) {
		cout << 0 << endl;
		return 0;
	}
	
	cin>>N;
	int i=1;
	for (;i<N+1;i++) {
		int xx, yy;
		cin >> xx >> yy;
		if (field[xx][yy]==INF)
			field[xx][yy]=i;
	}
	
	int lb=0, ub=1100, mid;
	while (ub-lb>1) {
		mid=(lb+ub)/2;
		if (search(mid))
			ub=mid;
		else
			lb=mid;
	}
	
	if (ub>N)
		cout << -1 << endl;
	else
		cout << ub << endl;
	
	return 0;
}