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 <vector>
#include <iostream>
#include <utility>
#include <algorithm>
#include <string>

using namespace std;
string map[1000];
int w, h;
vector<pair<int, int>> stack;
void f(int x, int y) {
	if (x < 0 || x >= w || y < 0 || y >= h||map[y][x]!='.')return;
	map[y][x] = 'o';
	stack.push_back(make_pair(x - 1, y));
	stack.push_back(make_pair(x, y - 1));
	stack.push_back(make_pair(x + 1, y));
	stack.push_back(make_pair(x, y + 1));
	return;
}
void g(int x, int y) {
	stack.push_back(make_pair(x, y));
	while (stack.size()) {
		auto a = stack.back();
		stack.pop_back();
		f(a.first, a.second);
	}
}
bool ch(int x, int y) {
	if (x < 0 || x >= w || y < 0 || y >= h)return false;
	return map[y][x] == 'o';
}
bool check(int x, int y) {
	return ch(x - 1, y) || ch(x, y - 1) || ch(x + 1, y) || ch(x, y + 1);
}
int main(){
	int n,tx,ty;
	cin >> w >> h;
	for (int i = 0; i < h; i++) {
		cin >> map[i];
	}
	cin >> n;
	for (int i = 0; i < h; i++) {
		size_t pos = map[i].find('t');
		if (pos == string::npos)continue;
		tx = pos, ty = i;
		break;
	}
	if (map[0][0] == 't') {
		cout << 0 << endl;
		return 0;
	}
	g(0, 0);
	if (check(tx, ty)) {
		cout << 0 << endl;
		return 0;
	}
	for (int i = 0; i < n; i++) {
		int x, y;
		cin >> x >> y;
		map[y][x] = '.';
		if (check(x, y)) {
			g(x, y);
		}
		if (check(tx, ty)) {
			cout << i + 1 << endl;
			return 0;
		}
	}
	cout << -1 << endl;
	return 0;
}