描述:帮助Joe走出迷宫。Joe每分钟可以向上下左右四个方向移动,所有着火的格子也会向四周蔓延。迷宫中的wall和着火点都不能进入,求Joe能够走出迷宫的最短时间,无法走出输出IMPOSSIBLE。
思路:bfs。由于有着火点会向四周蔓延,可先用bfs求出着火点蔓延到其他点的时间,(将所有着火点入队bfs)。后面再用bfs走迷宫时,只有从 出发开始经过时间小于着火时间的点才可以走,才能入队。两个bfs时间复杂度均为O(rc).
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
int dir[][2] = {-1, 0, 0, 1, 1, 0, 0, -1};
const int M = 1005, INF = 0x3f3f3f3f;
char map[M][M];
int r, c, fire[M][M]; //fire记录格点着火时间
bool vis[M][M];
struct Node {
int x, y, time;
};
Node now, next, start, Fire;
void pre_process()
{
queue<Node> q;
memset(map, 0, sizeof(map));
memset(fire, INF, sizeof(fire));
memset(vis, 0, sizeof(vis));
for (int i = 1; i <= r; ++i)
for (int j = 1; j <= c; ++j)
{
cin >> map[i][j];
if (map[i][j] == 'J')
start.x = i, start.y = j, start.time = 0;
else if (map[i][j] == 'F')
Fire.x = i, Fire.y = j, Fire.time = 0, fire[i][j] = 0, vis[i][j] = 1, q.push(Fire);
}
while (!q.empty())
{
now = q.front();
q.pop();
for (int i = 0; i < 4; ++i)
{
next.x = now.x + dir[i][0], next.y = now.y + dir[i][1], next.time = now.time + 1;
if (map[next.x][next.y] != 0 && !vis[next.x][next.y] && map[next.x][next.y] != '#')
{ //下标从1开始时可以用map[next.x][next.y] != 0代替判断next.x>=1 && next.x<=r && next.y>=1 && next.y<=c)
vis[next.x][next.y] = 1;
fire[next.x][next.y] = next.time;
q.push(next);
}
}
}
}
int bfs()
{
queue<Node> q;
memset(vis, 0, sizeof(vis));
q.push(start);
vis[start.x][start.y] = 1;
while (!q.empty())
{
now = q.front();
q.pop();
for (int i = 0; i < 4; ++i)
{
next.x = now.x + dir[i][0], next.y = now.y + dir[i][1], next.time = now.time + 1;
if (map[next.x][next.y] == 0)
return next.time;
if (map[next.x][next.y] != '#' && !vis[next.x][next.y] && next.time < fire[next.x][next.y])
{ //经过时间小于着火时间时改点才可走,入队
vis[next.x][next.y] = 1;
q.push(next);
}
}
}
return -1;
}
int main()
{
int T;
scanf("%d", &T);
while (T--)
{
scanf("%d %d", &r, &c);
pre_process();
int ans = bfs();
if (ans != -1)
printf("%d\n", ans);
else
printf("IMPOSSIBLE\n");
}
return 0;
}