第五次训练 G题

问题链接:Problem G

问题简述:

森林中J可向四个方向移动,同时火源向四个方向扩散,当J逃到地图外则视作成功逃离,问J能否逃离森林,若能,输出最短时间。

问题分析:

由最短路径可知,需要用到BFS。除了人外,森林中还有火源会随着人移动不断向四处扩散,则只需用两次BFS即可。第一个BFS模拟火源的移动,将火源扩散到每个方格时的最短时间记录下来,用于第二次人移动时的边境判断即可。若火源到达该方块的时间更早,则不能移动。

程序说明:

注意该题中可能有多个火源(这里WA了无!数!次),所以在第一个BFS使用时需要先将所有火源的位置压入队列,以便求得火源到达该方块时的最短路径。

AC通过的C语言程序如下:

#include<iostream>
#include<cstdio>
#include<cstdlib> 
#include<algorithm>
#include<queue>
#include<set>
#include<cstring>
#include<cmath>
using namespace std;
int fire[1005][1005];
bool vis[1005][1005];
char map[1005][1005];
int dir[4][2]={1,0,-1,0,0,1,0,-1};
int r,c;
struct node{
	int x;
	int y;
	int step;
};
bool edge(int x,int y){
	if(x>=0&&y>=0&&x<r&&y<c&&map[x][y]!='#'&&vis[x][y]==0){
		return 1;
		
	}
	else{
		return 0;
	}
}
bool check(int x,int y){
	if(map[x][y]!='F'&&map[x][y]!='#'&&vis[x][y]==0){
		return 1;
		
	}
	else{
		return 0;
	}
}
void BFSF(){
	queue<node>q;
	node p1;
	for(int i=0;i<r;i++){
		for(int j=0;j<c;j++){
			if(map[i][j]=='F'){
				p1.x=i;
				p1.y=j;
				p1.step=0;
				vis[i][j]=1;
				q.push(p1);
			}
		}
	}
	while(!q.empty()){
		node p2=q.front();
		q.pop();
		for(int i=0;i<4;i++){
			int next_x=p2.x+dir[i][0];
			int next_y=p2.y+dir[i][1];
			if(edge(next_x,next_y)){
				p1.x=next_x;
				p1.y=next_y;
				p1.step=p2.step+1;
				vis[p1.x][p1.y]=1;
				fire[p1.x][p1.y]=p1.step;
				q.push(p1);
			}
		}
	}
}
int BFS(int x,int y){
	queue<node>q;
	node p1;
	p1.x=x;
	p1.y=y;
	p1.step=0;
	vis[x][y]=1;
	q.push(p1);
	while(!q.empty()){
		node p2=q.front();
		q.pop();
		if(p2.x>=r||p2.y>=c||p2.x<0||p2.y<0){
			return p2.step;
		}
		for(int i=0;i<4;i++){
			p1.x=p2.x+dir[i][0];
			p1.y=p2.y+dir[i][1];
			p1.step=p2.step+1;
			if(check(p1.x,p1.y)){
				if(fire[p1.x][p1.y]!=0){
					if(fire[p1.x][p1.y]>p1.step){
						vis[p1.x][p1.y]=1;
						q.push(p1);
					}
				}
				else{
					vis[p1.x][p1.y]=1;
					q.push(p1);
				}
			}
		}
	}
	return -1;
}
int main(){
	std::ios::sync_with_stdio(false);
	int t;
	cin>>t;
	while(t--){
		cin>>r>>c;
		int jx,jy,fx,fy;
		for(int i=0;i<r;i++){
			for(int j=0;j<c;j++){
				cin>>map[i][j];
				if(map[i][j]=='J'){
					jx=i;
					jy=j;
				}
			}
		}
		memset(vis,0,sizeof(vis));
		memset(fire,0,sizeof(fire));
		BFSF();
		memset(vis,0,sizeof(vis));
		int ans=BFS(jx,jy);
		if(ans>=0){
			cout<<ans<<endl;
		}
		else{
			cout<<"IMPOSSIBLE"<<endl;
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值