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 <cstdio>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <bitset>
#include <numeric>
#include <climits>
#include <cfloat>
using namespace std;

int dy[] = {0, 1, -1, 0};
int dx[] = {-1, 0, 0, 1};

int main()
{
    int h, w;
    cin >> w >> h;
    vector<string> s(h);
    for(int i=0; i<h; ++i)
        cin >> s[i];

    int n;
    cin >> n;
    vector<vector<int> > open(h, vector<int>(w, -1));
    for(int i=0; i<n; ++i){
        int x, y;
        cin >> x >> y;
        open[y][x] = i+1;
    }

    vector<vector<bool> > check(h, vector<bool>(w, false));
    check[0][0] = true;
    vector<queue<pair<int, int> > > q(n+1);
    q[0].push(make_pair(0, 0));

    for(int i=0; i<=n; ++i){
        while(!q[i].empty()){
            int y0 = q[i].front().first;
            int x0 = q[i].front().second;
            q[i].pop();

            if(s[y0][x0] == 't'){
                cout << i << endl;
                return 0;
            }

            for(int j=0; j<4; ++j){
                int t = i;
                int y = y0 + dy[j];
                int x = x0 + dx[j];
                if(y < 0 || y >= h || x < 0 || x >= w || check[y][x])
                    continue;
                if(s[y][x] == '#'){
                    if(open[y][x] == -1)
                        continue;
                    t = max(t, open[y][x]);
                }
                check[y][x] = true;
                q[t].push(make_pair(y, x));
            }
        }
    }

    cout << -1 << endl;
    return 0;
}