注意:
(1)加上火之后,预处理出每个格子的最早着火时间,当Joe走到格子时,进行判断能否走即可。
(2)刚开始的着火点有多个,如何同时求在多个着火点的情况下的最早着火时间。
考虑建造一个超级源,连向出始得着火点,则一次广搜即可。
思考可以建造超级源的条件???
每个着火点的蔓延过程是相互独立的,且每个格子最小着火时间即所有着火点蔓延到该格子时间的最小值。
//#pragma warning (disable: 4786)
//#pragma comment (linker, "/STACK:16777216")
//HEAD
#include <cstdio>
#include <ctime>
#include <cstdlib>
#include <cstring>
#include <queue>
#include <string>
#include <set>
#include <stack>
#include <map>
#include <cmath>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
//LOOP
#define FE(i, a, b) for(int i = (a); i <= (b); ++i)
#define FD(i, b, a) for(int i = (b); i>= (a); --i)
#define REP(i, N) for(int i = 0; i < (N); ++i)
#define CLR(A,value) memset(A,value,sizeof(A))
#define CPY(a, b) memcpy(a, b, sizeof(a))
#define FC(it, c) for(__typeof((c).begin()) it = (c).begin(); it != (c).end(); it++)
//INPUT
#define RI(n) scanf("%d", &n)
#define RII(n, m) scanf("%d%d", &n, &m)
#define RIII(n, m, k) scanf("%d%d%d", &n, &m, &k)
#define RS(s) scanf("%s", s)
//OUTPUT
#define WI(n) printf("%d\n", n)
#define WS(s) printf("%s\n", s)
typedef long long LL;
const int INF = 0x3f3f3f3f;
const double eps = 1e-10;
const int maxn = 20;
typedef pair<int, int> pii;
queue<pii>Q;
pii st;
struct node{
pii x;
int dis;
node(pii x, int dis): x(x), dis(dis){}
};
queue<node>q;
char s[1010];
int tab[1010][1010];
int n, m;
int dir_i[4] = {1, -1, 0, 0};
int dir_j[4] = {0, 0, 1, -1};
bool vis[1010][1010];
bool check(int x, int y)
{
if (x < 0 || x >= n || y < 0 || y >= m) return false;
return true;
}
int main ()
{
int T;
scanf("%d",&T);
while (T--)
{
while (!Q.empty()) Q.pop();
while (!q.empty()) q.pop();
memset(vis, 0, sizeof(vis));
memset(tab, INF, sizeof(tab));
scanf("%d%d", &n, &m);
for (int i = 0; i < n; i++)
{
scanf("%s", s);
for (int j = 0; j < m; j++)
{
if (s[j] == '#') tab[i][j] = 0;
else if (s[j] == 'F')
{
Q.push(make_pair(i, j));
tab[i][j] = 0;
}
else if (s[j] == 'J')
st = make_pair(i, j);
}
}
while (!Q.empty())
{
pii x = Q.front(); Q.pop();
for (int r = 0; r < 4; r++)
{
int ni = x.first + dir_i[r];
int nj = x.second + dir_j[r];
if (check(ni, nj) && tab[ni][nj] > tab[x.first][x.second] + 1)
{
tab[ni][nj] = tab[x.first][x.second] + 1;
Q.push(make_pair(ni, nj));
}
}
}
q.push(node(st, 0));
vis[st.first][st.second] = true;
int fla = 0, ans;
if (st.first == 0 || st.first == n - 1 || st.second == 0 || st.second == m - 1)
{
fla = 1;
ans = 1;
}
while (!q.empty())
{
if (fla) break;
node a = q.front(); q.pop();
pii x = a.x;
int nextx = a.dis + 1;
for (int r = 0; r < 4; r++)
{
int ni = x.first + dir_i[r];
int nj = x.second + dir_j[r];
if (check(ni, nj) && !vis[ni][nj] && tab[ni][nj] > nextx)
{
if (ni == 0 || ni == n - 1 || nj == 0 || nj == m - 1)
{
fla = 1;
ans = nextx + 1;
break;
}
vis[ni][nj] = true;
q.push(node(make_pair(ni, nj), nextx));
}
}
}
if (fla) printf("%d\n", ans);
else puts("IMPOSSIBLE");
}
return 0;
}