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:
/*
 * 2364.cc: Lucky Dip
 */

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<stack>
#include<list>
#include<queue>
#include<deque>
#include<algorithm>
#include<numeric>
#include<utility>
#include<complex>
#include<functional>
 
using namespace std;

/* constant */

const int MAX_W = 1000;
const int MAX_H = 1000;

const int INF = 1 << 30;

const int dxs[] = {1, 0, -1, 0}, dys[] = {0, -1, 0, 1};

/* typedef */

struct Stat {
  int d, x, y;
  Stat() {}
  Stat(int _d, int _x, int _y): d(_d), x(_x), y(_y) {}
  bool operator<(const Stat &s) const { return d > s.d; }
};

/* global variables */

int flds[MAX_H][MAX_W], dists[MAX_H][MAX_W];

/* subroutines */

/* main */

int main() {
  int w, h;
  cin >> w >> h;

  int gx, gy;

  for (int y = 0; y < h; y++) {
    string s;
    cin >> s;
    for (int x = 0; x < w; x++) {
      switch(s[x]) {
      case '.': flds[y][x] = 0; break;
      case '#': flds[y][x] = INF; break;
      case 't': flds[y][x] = 0; gx = x; gy = y; break;
      }
      dists[y][x] = INF;
    }
  }

  int n;
  cin >> n;
  for (int i = 1; i <= n; i++) {
    int x, y;
    cin >> x >> y;
    if (flds[y][x]) flds[y][x] = i;
  }

  dists[0][0] = 0;

  priority_queue<Stat> q;
  q.push(Stat(0, 0, 0));

  while (! q.empty()) {
    Stat u = q.top(); q.pop();
    if (dists[u.y][u.x] != u.d) continue;
    if (u.x == gx && u.y == gy) break;

    for (int di = 0; di < 4; di++) {
      int vx = u.x + dxs[di], vy = u.y + dys[di];
      if (vx >= 0 && vx < w && vy >= 0 && vy < h && flds[vy][vx] < INF) {
	int vd = max(u.d, flds[vy][vx]);
	if (dists[vy][vx] > vd) {
	  dists[vy][vx] = vd;
	  q.push(Stat(vd, vx, vy));
	}
      }
    }
  }

  printf("%d\n", (dists[gy][gx] < INF) ? dists[gy][gx] : -1);
  return 0;
}