题目链接:
https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2671
题目大意:J代表Joe的位置,F代表火的起点,每一分钟火将会向四周扩散,每一分钟joe可以走一格,#火和joe都不能通过,求Joe逃离的最短时间,如果不能逃离输出IMPOSSIBLE
思路:简单BFS,先用fire数组确定火走到每个点最小步数,fire数组最开始为无穷大,再bfs一次joe的路径,如果当前步数小于火烧到这个位置,那么可走
特别注意:火的位置可能有多个!!!
被坑惨了,wa了四发
代码:
#include<cstdio>
#include<cmath>
#include<cstring>
#include<string>
#include<cstdlib>
#include<algorithm>
#include<iostream>
#include<queue>
#include<stack>
using namespace std;
#define FOU(i,x,y) for(int i=x;i<=y;i++)
#define FOD(i,x,y) for(int i=x;i>=y;i--)
#define MEM(a,val) memset(a,val,sizeof(a))
#define PI acos(-1.0)
const double EXP = 1e-9;
typedef long long ll;
typedef unsigned long long ull;
const int INF = 0x3f3f3f3f;
const ll MINF = 0x3f3f3f3f3f3f3f3f;
const int mod = 1e9+7;
const int N = 1e6+5;
int n,m;
int mp[1005][1005];
int fire[1005][1005]; //记录火烧的时间
int vis[1005][1005];
int dir[4][2]={0,1,0,-1,1,0,-1,0};
struct node
{
int x,y;
int step;
}s,f;
queue<node>Q;
bool check(int x,int y)
{
if(x<=0||x>n||y<=0||y>m||vis[x][y]==1||mp[x][y]=='#')
return false;
return true;
}
void bfs1()
{
node now,next;
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.step=now.step+1;
if(check(next.x,next.y))
{
vis[next.x][next.y]=1;
fire[next.x][next.y]=next.step;
Q.push(next);
}
}
}
}
int bfs()
{
MEM(vis,0); //搜索joe的时候初始化vis数组
queue<node>q;
node now,next;
now.x=s.x;
now.y=s.y;
now.step=1;
vis[now.x][now.y]=1;
q.push(now);
while(!q.empty())
{
now=q.front();
q.pop();
if(now.x==1||now.x==n||now.y==1||now.y==m)
return now.step;
for(int i=0;i<4;i++)
{
next.x=now.x+dir[i][0];
next.y=now.y+dir[i][1];
next.step=now.step+1;
if(check(next.x,next.y)&&next.step<fire[next.x][next.y])
{
vis[next.x][next.y]=1;
q.push(next);
}
}
}
return -1;
}
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
//std::ios::sync_with_stdio(false);
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
MEM(fire,INF); //最开始把每个点初始化为无穷大
MEM(vis,0); //第一次搜索火的时候初始化vis数组
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
scanf(" %c",&mp[i][j]);
if(mp[i][j]=='J')
{
s.x=i;
s.y=j;
}
if(mp[i][j]=='F')
{
node now;
now.x=i;
now.y=j;
now.step=1;
vis[i][j]=1;
fire[i][j]=1;
Q.push(now);
}
}
}
bfs1(); //广搜火燃到每一个点需要的时间
int ans = bfs(); //枚举joe的步数
if(ans==-1)
printf("IMPOSSIBLE\n");
else
printf("%d\n",ans);
}
return 0;
}