Fire!

Fire!

题意:给定一个大火蔓延的迷宫,问joe能否走出去,如果能输出最少时间。

思路:两次bfs,第一次记录每块盒子被火烧到的时间,第二次进行逃跑路线的bfs 

#include<bits/stdc++.h>
using namespace std;
const int inf=0x3f3f3f3f;
int dir[4][2]={{-1,0},{1,0},{0,1},{0,-1}};
int n,m,s,e;
bool vis[1005][1005];
int times[1005][1005];
int step[1005][1005];
char a[1005][1005];
struct node{
	int x,y;
	node(){};
	node(int _x,int _y):x(_x),y(_y){}
};
queue<node>q;
bool check(int x,int y){
	if(x<0||x>=n||y<0||y>=m)
		return false;
	if(vis[x][y])
		return false;
	return a[x][y]=='.';
}
void bfs_fire(){
	while(!q.empty()){
		node p=q.front();
		q.pop();
		for(int i=0;i<4;i++){
			int xx=p.x+dir[i][0];
			int yy=p.y+dir[i][1];
			if(check(xx,yy)){
				vis[xx][yy]=true;
				times[xx][yy]=times[p.x][p.y]+1;
				q.push(node(xx,yy));
			}
		}
	}
}
int bfs(int x,int y){
	step[x][y]=0;
	q.push(node(x,y));
	vis[x][y]=true;
	while(!q.empty()){
		node p=q.front();
		q.pop();
		if(p.x==0||p.x==n-1||p.y==0||p.y==m-1)
			return step[p.x][p.y]+1;
			
		for(int i=0;i<4;i++){
			int xx=p.x+dir[i][0];
			int yy=p.y+dir[i][1];
			if(check(xx,yy)&&step[p.x][p.y]+1<times[xx][yy]){
				step[xx][yy]=step[p.x][p.y]+1;
				vis[xx][yy]=true;
				q.push(node(xx,yy));
			}
		}
	}
	return -1;
}
int main(){
	ios::sync_with_stdio(false);
	int t;
	cin>>t;
	while(t--){
		cin>>n>>m;
		memset(times,inf,sizeof(times));
		memset(vis,false,sizeof(vis));
		for(int i=0;i<n;i++){
			for(int j=0;j<m;j++){
				cin>>a[i][j];
				if(a[i][j]=='J'){
					s=i;
					e=j;
				}
				if(a[i][j]=='F'){
					vis[i][j]=true;
					q.push(node(i,j));
					times[i][j]=0;
				}
			}
		}
		bfs_fire();
		while(!q.empty())
			q.pop();
		memset(vis,false,sizeof(vis));
		int ans=bfs(s,e);
		if(ans==-1)
			cout<<"IMPOSSIBLE\n";
		else cout<<ans<<"\n"; 
		
	}
	return 0; 
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值