解题思路
一个多起点的两类的bfs,火起点,Joe 的起点。火起点可以是多个。Joe起点只有一个。必须是先遍历火起点,后是Joe起点。因为当同一时刻,火烧的地方和Joe到的地方是同一地点,这时Joe会死,但相对Joe上一个状态量来说,又是其中之一的子状态,完全可以更换一个子状态以达到存活更久的目的。就是说,Joe换位置,必须依赖于此刻火的蔓延情况,所以得知,应该先遍历火起点后是Joe起点。
相对于基础模板来说,只是入队的时候判断的条件多一些,分类入队。
其中,需要避免一开始,Joe就被烧死的情况。所以需要出队后,立刻判断他死不死。
题解代码
#include<iostream>
#include<queue>
#include<cstring>
#include<string>
#include<map>
#include<vector>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstdlib>
#include<stack>
#include<ctime>
using namespace std;
#define rep(i,aa,bb) for(register int i=aa;i<=bb;i++)
#define rrep(i,aa,bb) for(register int i=aa;i>=bb;i--)
#define LL long long
#define eps 0.000001
#define inf 0x3f3f3f3f
#define exp 0.000001
#define pai 3.141592654
#define random(x) rand()%(x)
#define lowbit(x) x&(-x)
inline int read()
{
int x=0,y=1;char a=getchar();while ( a>'9' || a<'0'){if ( a=='-')y=-1;a=getchar();}
while ( a>='0' && a<='9' ){ x=10*x+a-'0'; a=getchar();}return x*y;
}
#define N 1005
char e[1005][1005];int n,m;
struct node {
int x,y,t; char j_f;
};
queue<node>q;
bool vis[N][N],isfire[N][N];
const int nxt[][2] = { 1,0,-1,0,0,1,0,-1};
bool isout(int x,int y){
if ( x <= 0 || x > n ) return 1;
if ( y <= 0 || y > m ) return 1;
return 0;
}
void bfs(){
while ( q.empty() == 0 ){
node now,nex;
now = q.front();
q.pop();
if ( now.j_f == 'J' && isfire[now.x][now.y] ){
printf("IMPOSSIBLE\n");
return ;
}
rep(i,0,3){
nex.x = now.x + nxt[i][0];
nex.y = now.y + nxt[i][1];
nex.t = now.t + 1;
nex.j_f = now.j_f;
if ( nex.j_f == 'F' ){
if ( isout(nex.x,nex.y) ) continue;
if ( vis[nex.x][nex.y] ) continue;
if ( e[nex.x][nex.y] == '#') continue;
vis[nex.x][nex.y] = 1;
isfire[nex.x][nex.y] = 1;
q.push(nex);
}
else if ( nex.j_f == 'J'){
if ( isout(nex.x,nex.y) ){
printf("%d\n",nex.t);
return ;
}
if ( vis[nex.x][nex.y] ) continue;
if ( e[nex.x][nex.y] == '#') continue;
if ( isfire[nex.x][nex.y] ) continue;
vis[nex.x][nex.y] = 1;
q.push(nex);
}
}
}
printf("IMPOSSIBLE\n");
}
void init(){
memset(isfire,0,sizeof(isfire));
memset(vis,0,sizeof(vis));
memset(e,0,sizeof(e));
while ( q.empty() == 0 ) q.pop();
}
int main()
{
// freopen("1.txt","r",stdin);
int t;
t = read();
while ( t-- ){
init();
n = read(); m = read();
rep(i,1,n)
scanf("%s",e[i]+1);
int jx,jy;
rep(i,1,n) rep(j,1,m){
if( e[i][j] == 'J')
jx = i, jy = j;
else if ( e[i][j] == 'F'){
node tema ;
tema.x = i; tema.y = j; tema.t = 0; tema.j_f = 'F';
isfire[i][j] = true;
q.push(tema);
}
}
node tema ;
tema.x = jx; tema.y = jy; tema.t = 0; tema.j_f = 'J';
vis[jx][jy] = true;
q.push(tema);
bfs();
}
return 0;
}
注意
1、队列要排空。
2、各类初始化。