题目描述
贪玩的吉米又去玩迷宫游戏了,这次迷宫里除了吉米,还有一只火焰精灵(火焰精灵有且只有一只)。对于吉米来说,他从一个房间走到下一个房间需要一分钟。对于火焰精灵,它会不断放出火焰,一旦某个房间着火了,下一分钟这个房间上下左右四个房间都会着火。火焰的范围不会超出迷宫,所以迷宫外都是安全的区域。
迷宫可以用一个n*m的字符矩阵来表示,如果第i行j列为’.’,表示这个房间可以通行。
如果第i行j列为’#’,表示这个位置是障碍物,障碍物不会被燃烧。
如果第i行j列为’J’,表示吉米在这个房间。
如果第i行j列为’F’,表示火焰精灵在这个房间。
吉米的目标就是安全逃出这个迷宫,当吉米的位置(x,y) 不在迷宫的范围内时,便认为吉米逃出了迷宫。
注意,火焰精灵一开始所在的房间是着火的。
输入格式
第一行包括两个正整数n,m ( 1 <= n,m <= 1000),表示迷宫为n行m列
接下来有一个n*m的字符矩阵,表示迷宫
输出格式
如果吉米可以逃出迷宫,输出吉米用的最小时间,否则输出”IMPOSSIBLE”.
样例输入
4 4
####
#JF#
#..#
#..#
样例输出
3
此题的妙点在于将火灵和小吉吉的路径都分开进行dfs,然后在小吉吉的路径中进行ans的处理,然后最重要的就是小吉吉想要通过这一条路就必须得比火灵先到达所以(step2[f.x][f.y] + 1 < step[nx][ny])//就是这一段(71行代码),才能继续进行
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <vector>
#include <map>
#include <stack>
#include <queue>
#include <set>
using namespace std;
typedef long long ll;
const int maxx = 2023;
const int INF = 0x3f3f3f3f;
char a[maxx][maxx];
int step[maxx][maxx], step2[maxx][maxx];//吉米和火零
int x1, x2, y1, y2;
int n, m;
int dx[] = { -1, 1, 0, 0 };//方向
int dy[] = { 0, 0, 1, -1 };
struct check//进行初始化
{
int x, y;
check(int xx = 0, int yy = 0)
{
x = xx;
y = yy;
}
};
void bfs1()//火灵的路径
{
memset(step, 0x3f, sizeof(step));
queue<check> q;
q.push(check(x1, y1));
step[x1][y1] = 0;
while (!q.empty())
{
check f = q.front();
q.pop();
for (int i = 0; i < 4; i++)//依次进行
{
int nx = f.x + dx[i];
int ny = f.y + dy[i];
if (nx >= 0 && ny >= 0 && ny < m && nx < n)//未越界
{
if (a[nx][ny] != '#' && step[nx][ny] == 0x3f3f3f3f)
{
q.push(check(nx, ny));
step[nx][ny] = step[f.x][f.y] + 1;//对应位置步数++
}
}
}
}
}
int bfs2()
{
memset(step2, 0x3f, sizeof(step2));//初始化
queue <check> q;
q.push(check(x2, y2));
step2[x2][y2] = 0;
while (!q.empty())
{
check f = q.front();
q.pop();
for (int i = 0; i < 4; i++)
{
int nx = f.x + dx[i];
int ny = f.y + dy[i];
if (nx >= 0 && ny >= 0 && nx < n && ny < m)
{
if (a[nx][ny] != '#' && step2[nx][ny] == 0x3f3f3f3f && step2[f.x][f.y] + 1 < step[nx][ny])//在之前的前提下还得
{ //比在火侵蚀之前到达
q.push(check(nx, ny));
step2[nx][ny] = step2[f.x][f.y] + 1;//时间++
}
}
else//越界了就逃出了
{
return step2[f.x][f.y] + 1;//最后一步
}
}
}
return -1;//没能逃出
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> m;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)//取出位置
{
cin >> a[i][j];
if (a[i][j] == 'F')
{
x1 = i;
y1 = j;
}
else if (a[i][j] == 'J')
{
x2 = i;
y2 = j;
}
}
}
bfs1();
int ans = bfs2();//最短 时间
if (ans == -1)
{
cout << "IMPOSSIBLE" << endl;
}
else
{
cout << ans << endl;
}
return 0;
}//妙妙妙