题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2671
题目大意:Joe被困在火里面,火向四周蔓延,Joe可以向上下左右移动,当Joe走到图的边界时,我们可以认为他走出了迷宫。
用广搜写,将火的路径预处理一下,再看看Joe能不能逃出
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
char map[1010][1010];
int step[1010][1010];
int book[1010][1010];
int n,m;
int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
struct Node{
int x,y,step;
};
Node start,hehe;
queue<Node> fire;
void Firebfs(){
Node a,b;
while(!fire.empty()){
a=fire.front();
fire.pop();
step[a.x][a.y]=a.step;
for(int i=0;i<4;i++){
b.x=a.x+dir[i][0];
b.y=a.y+dir[i][1];
b.step=a.step+1;
if(b.x>=0&&b.y>=0&&b.x<n&&b.y<m&&!book[b.x][b.y]&&map[b.x][b.y]!='#'){
book[b.x][b.y]=1;
fire.push(b);
}
}
}
}
int bfs(){
queue<Node> que;
que.push(start);
memset(step,9999,sizeof(step));
//对火进行处理
Firebfs();
memset(book,0,sizeof(book));
Node a,b;
while(!que.empty()){
a=que.front();
que.pop();
if(a.x==0||a.y==0||a.x==n-1||a.y==m-1){
return a.step+1;
}
for(int i=0;i<4;i++){
b.x=a.x+dir[i][0];
b.y=a.y+dir[i][1];
b.step=a.step+1;
if(b.x>=0&&b.x<n&&b.y>=0&&b.y<m&&step[b.x][b.y]>b.step&&map[b.x][b.y]=='.'&&!book[b.x][b.y]){
//step[b.x][b.y]>b.step表示在火烧到之前人已经到达
book[b.x][b.y]=1;
que.push(b);
}
}
}
return 0;
}
int main(){
int t;
cin>>t;
while(t--){
memset(book,0,sizeof(book));
scanf("%d%d",&n,&m);
for(int i=0;i<n;i++){
scanf("%s",&map[i]);
}
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(map[i][j]=='J'){
start.x=i;
start.y=j;
start.step=0;
}
if(map[i][j]=='F'){
hehe.x=i;
hehe.y=j;
hehe.step=0;
book[i][j]=1;
fire.push(hehe);
}
}
}
int ans=bfs();
if(!ans) cout<<"IMPOSSIBLE"<<endl;
else cout<<ans<<endl;
}
}