一.题目链接:
UVA-11624
二.题目大意:
给你一个 N × M 的图,图由以下符号组成.
'#':墙
'.':空地
'F':火
'J':起点
每时刻,火会向四周延展(墙可阻隔火的延展)
每时刻,人可以向四周任意一个方向移动.
当人到达边界时,人再走一步即可逃离.
求最少需要多少时间,人能够逃离,如果不能逃离,则输出 "IMPOSSIBLE".
三.分析:
就是在普通的 BFS 里面,模拟火的延展,具体看代码.
四.代码实现:
#include <set>
#include <map>
#include <ctime>
#include <queue>
#include <cmath>
#include <stack>
#include <vector>
#include <cstdio>
#include <sstream>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#define eps 1e-6
#define pi acos(-1.0)
#define ll long long int
using namespace std;
const int M = (int)1e3;
const int inf = 0x3f3f3f3f;
struct node
{
int x;
int y;
int step;
};
queue <node> fire;
char mp[M + 5][M + 5];
bool vis[M + 5][M + 5];
int Move[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
int bfs(struct node cur, int n, int m)
{
struct node p, t;
queue <node> q;
vis[cur.x][cur.y] = 1;
q.push(cur);
int times = -1;
while(!q.empty())
{
cur = q.front();
q.pop();
if(cur.x == 1 || cur.y == 1 || cur.x == n || cur.y == m)
return cur.step + 1;
if(times != cur.step)
{
times = cur.step;
int len = fire.size();
while((len--) > 0)
{
p = fire.front();
fire.pop();
for(int i = 0; i < 4; ++i)
{
t = p;
t.x += Move[i][0];
t.y += Move[i][1];
if(t.x >= 1 && t.x <= n && t.y >= 1 && t.y <= m && mp[t.x][t.y] != '#' && mp[t.x][t.y] != 'F')
{
mp[t.x][t.y] = 'F';
fire.push(t);
}
}
}
}
for(int i = 0; i < 4; ++i)
{
t = cur;
t.x += Move[i][0];
t.y += Move[i][1];
if(t.x >= 1 && t.x <= n && t.y >= 1 && t.y <= m && mp[t.x][t.y] == '.' && !vis[t.x][t.y])
{
t.step++;
vis[t.x][t.y] = 1;
q.push(t);
}
}
}
return -1;
}
int main()
{
int T;
scanf("%d", &T);
for(int ca = 1; ca <= T; ++ca)
{
while(!fire.empty())
fire.pop();
memset(vis, 0, sizeof(vis));
int n, m;
scanf("%d %d", &n, &m);
struct node start;
for(int i = 1; i <= n; ++i)
{
getchar();
for(int j = 1; j <= m; ++j)
{
mp[i][j] = getchar();
if(mp[i][j] == 'F')
{
struct node p;
p.x = i;
p.y = j;
p.step = 0;
fire.push(p);
}
else if(mp[i][j] == 'J')
{
start.x = i;
start.y = j;
start.step = 0;
}
}
}
int step = bfs(start, n, m);
if(~step)
printf("%d\n", step);
else
printf("IMPOSSIBLE\n");
}
return 0;
}