Joe works in a maze. Unfortunately,portions of the maze have caught on fire, and the owner of the maze neglectedto create a fire escape plan. Help Joe escape the maze.
Given Joe's location in the maze and which squares of themaze are on fire, you must determine whether Joe can exit the maze before thefire 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 fourdirections from each square that is on fire. Joe may exit the maze from anysquare that borders the edge of the maze. Neither Joe nor the fire may enter asquare that is occupied by a wall.
Input Specification
The first line of input contains a single integer, thenumber of test cases to follow. The first line of each test case contains thetwo integers R and C, separated byspaces, with 1 <= R,C <= 1000. Thefollowing R lines of the test case each contain one row of themaze. Each of these lines contains exactly C characters, andeach of these characters is one of:
· #, a wall
· ., a passable square
· J, Joe's initialposition in the maze, which is a passable square
· F, a square that is onfire
There will be exactly one J in each test case.
Input
2
4 4
####
#JF#
#..#
#..#
3 3
###
#J.
#.F
Output
3
IMPOSSIBLE
注意加粗的红色字体,火源不一定只有一个
然后先让火广搜一次,标记一下到达某个点的最短时间
然后再让Joe广搜,只要到达某个点的时间比火到达的时间短就可以
这样两次bfs就ok了
今天把之前的题补了,突然发现竟然是一年前做的题
注意标记数组初始化的问题
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <set>
#define INF 0x3f3f3f3f
using namespace std;
const int maxn=1e5+5;
typedef long long ll;
char s[1005][1005];
int vis[1005][1005],vis1[1005][1005],n,m,f;
struct node
{
int a,b,step;
node(){}
node(int c,int d,int e){
a=c;b=d;step=e;
}
};
int dir[4][2]={0,1,1,0,-1,0,0,-1};
void init()
{
memset(vis,INF,sizeof(vis));
memset(vis1,INF,sizeof(vis1));
f=0;
}
void fbfs(int a,int b)
{
vis[a][b]=1;
queue<node> q;
q.push(node(a,b,vis[a][b]));
while(!q.empty())
{
//cout<<12313<<endl;
node pos=q.front();
q.pop();
int t=pos.step;
for(int i=0;i<4;i++)
{
int x=pos.a+dir[i][0];
int y=pos.b+dir[i][1];
if(x<0||y<0||x>=n||y>=m||s[x][y]=='F')continue;
if(s[x][y]=='#')continue;
if(vis[x][y]>t+1)
{
vis[x][y]=t+1;
q.push(node(x,y,vis[x][y]));
}
}
}
}
void bfs(int a,int b)
{
vis1[a][b]=1;
queue<node> q;
q.push(node(a,b,1));
while(!q.empty())
{
node pos=q.front();
q.pop();
int t=pos.step;
for(int i=0;i<4;i++)
{
int x=pos.a+dir[i][0];
int y=pos.b+dir[i][1];
if(x<0||y<0||x>=n||y>=m)
{
f=1;
printf("%d\n",t);
return;
}
if(s[x][y]=='#'||s[x][y]=='F')continue;
if(vis1[x][y]!=INF)continue;
if(vis[x][y]>t+1)
{
vis1[x][y]=t+1;
q.push(node(x,y,vis1[x][y]));
}
}
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
getchar();
init();
int sx,sy;
for(int i=0;i<n;i++)
scanf("%s",s[i]);
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(s[i][j]=='F')
{
fbfs(i,j);
}
if(s[i][j]=='J')
sx=i,sy=j;
}
}
bfs(sx,sy);
if(!f)
printf("IMPOSSIBLE\n");
}
return 0;
}