迷宫中有障碍格、火格。着火的格子每分钟向上下左右四个方向蔓延。问能否走出迷宫,求最短时间。
简单BFS,见大白书307页。
#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long uLL;
typedef long long LL;
typedef double db;
#define inf 0x3f3f3f3f
char m[1005][1005];
int T1[1005][1005],T2[1005][1005],r,c;
int mov[4][2]= {{1,0},{-1,0},{0,1},{0,-1}};
struct point
{
int x,y;
};
void bfs1()
{
queue<point> q;
memset(T1,-1,sizeof(T1));
int i,j;
for(i=0;i<r;++i)
for(j=0;j<c;++j)
{
if(m[i][j]=='F')
{
point tem;
tem.x=i,tem.y=j;
q.push(tem);
T1[i][j]=0;
}
}
while(!q.empty())
{
point p=q.front();
q.pop();
for(i=0;i<4;++i)
{
point tem=p;
tem.x+=mov[i][0];
tem.y+=mov[i][1];
if(tem.x>=0&&tem.y>=0&&tem.x<r&&tem.y<c&&m[tem.x][tem.y]!='#'&&T1[tem.x][tem.y]==-1)
{
q.push(tem);
T1[tem.x][tem.y]=T1[p.x][p.y]+1;
}
}
}
}
int bfs2()
{
queue<point> q;
memset(T2,-1,sizeof(T2));
int i,j;
for(i=0;i<r;++i)
for(j=0;j<c;++j)
{
if(m[i][j]=='J')
{
point tem;
tem.x=i,tem.y=j;
q.push(tem);
T2[i][j]=0;
}
}
while(!q.empty())
{
point p=q.front();
q.pop();
if(p.x==0||p.y==0||p.x==r-1||p.y==c-1) return T2[p.x][p.y]+1;
for(i=0;i<4;++i)
{
point tem=p;
tem.x+=mov[i][0];
tem.y+=mov[i][1];
if(T2[tem.x][tem.y]!=-1) continue;
T2[tem.x][tem.y]=T2[p.x][p.y]+1;
if(tem.x>=0&&tem.y>=0&&tem.x<r&&tem.y<c&&m[tem.x][tem.y]!='#'&&(T1[tem.x][tem.y]==-1||T1[tem.x][tem.y]>T2[tem.x][tem.y])) //这里得注意火被隔断的情况。即并不是每个空格都可能着火(如果被火格障碍物隔断则某些格子T1始终为0))
q.push(tem);
}
}
return -1;
}
int main()
{
int i,t;
cin>>t;
while(t--)
{
scanf("%d%d",&r,&c);
queue<point> q;
for(i=0; i<r; ++i) scanf("%s",m[i]);
bfs1();
int ans=bfs2();
if(ans==-1) puts("IMPOSSIBLE");
else printf("%d\n",ans);
}
return 0;
}