描述
Joe works in a maze. Unfortunately, portions of the maze have caught on fire, and the owner of the maze neglected to create a fire escape plan. Help Joe escape the maze.
Given Joe’s location in the maze and which squares of the maze are on fire, you must determine whether Joe can exit the maze before the fire reaches him, and how fast he can do it.
Joe and the fire each move one square per minute, vertically or horizontally (not diagonally). The fire spreads all four directions from each square that is on fire. Joe may exit the maze from any square that borders the edge of the maze. Neither Joe nor the fire may enter a square that is occupied by a wall.
输入
The first line of input contains the two integers R and C, separated by spaces, with 1 <= R,C <= 1000. The following R lines of input each contain one row of the maze. Each of these lines contains exactly C characters, and each of these characters is one of:
#, a wall
., a passable square
J, Joe’s initial position in the maze, which is a passable square
F, a square that is on fire
There will be exactly one J in the input.
输出
Output a single line containing IMPOSSIBLE if Joe cannot exit the maze before the fire reaches him, or an integer giving the earliest time Joe can safely exit the maze, in minutes.
样例输入
4 4
#JF#
#…#
#…#
样例输出
3
提示
Another sample input and output:
Sample Input
3 3
#J.
#.F
Sample Output
IMPOSSIBLE
题解
要注意会有多个着火的地方,然后分别对人和火BFS可以了。具体看代码
代码
#include <bits/stdc++.h>
using namespace std;
int dir[][2]={1,0,-1,0,0,1,0,-1};
struct node
{
int st,x,y;
};
queue<node>que1;//BFS人用的队列
queue<node>que2;//BFS火用的队列
char mp[1005][1005];
bool vis[1005][1005];//用来标记是否走过
int r,c;
int main()
{
scanf("%d %d",&r,&c);
for(int i=1;i<=r;i++)
{
getchar();
for(int j=1;j<=c;j++)
{
mp[i][j]=getchar();
if(mp[i][j]=='J')
{
que1.push((node){0,i,j});//入队
vis[i][j]=1;
}
if(mp[i][j]=='F')
que2.push((node){0,i,j});//着火点入队
}
}
node s,t;
node a,b;
while(!que1.empty())
{
s=que1.front();
que1.pop();
if(s.x>r||s.y<1||s.x<1||s.y>c)//判断是否跑出去
{
printf("%d\n",s.st);
return 0;
}
t.st=s.st+1;
for(int i=0;i<4;i++)
{
t.x=s.x+dir[i][0];
t.y=s.y+dir[i][1];
if(mp[t.x][t.y]!='#'&&mp[t.x][t.y]!='F'&&mp[t.x-1][t.y]!='F'&&mp[t.x+1][t.y]!='F'&&mp[t.x][t.y+1]!='F'&&mp[t.x][t.y-1]!='F'&&vis[t.x][t.y]==0)//判断走的点是否合法
//1.不能是墙,即地图标记不为‘#’
//2.走的点不能着火
//3.走的点四周没有着火点,不然同一时间就会在该点着火
{
vis[t.x][t.y]=1;//合法入队
que1.push(t);
}
}
while(!que2.empty())//对着火点BFS
{
a=que2.front();
if(a.st!=s.st)//只BFS步数与人相同的着火点
break;
que2.pop();
b.st=a.st+1;
for(int i=0;i<4;i++)
{
b.x=a.x+dir[i][0];
b.y=a.y+dir[i][1];
if(mp[b.x][b.y]=='.')
{
mp[b.x][b.y]='F';
que2.push(b);
}
}
}
}
printf("IMPOSSIBLE\n");//如果队列都跑空,就输出这个
}
备注
也可以先用数组把第几步的时候该点会着火标记下来,然后再BFS人。人到每个点的步数要小于着火的步数。