UVA11624 Fire! (两次BFS) 读懂题意很重要

题目:https://uva.onlinejudge.org/index.phpoption=com_onlinejudge&Itemid=8&page=show_problem&problem=2671

题意:就是迷宫着火了,火势会蔓延,Joe要逃跑,看最后能不能逃出来,但没想到败在了英语上,大家注意,题意中用的是portions,这是一个复数形式,也就是说,Joe的起点唯一,但是起火的地方并不是唯一的,这是我们首先要明确的。

思路:之前好像做到过类似的题目,当时很多人都a了,但是我没有比较好的思路,所以这次比赛的时候就看都没敢看,今日补题,觉得挺简单的啊~~~。

总的来说,就是从多个F,开始预处理出每个位置将着火的时间,然后再bfs出J位置到出口的最少时间,思路还是比较清晰的,代码也比较好写,但是不要忘记初始化时间数组,vis数组,两个队列。

代码:

#include<cstdio>
#include<queue>
#include<string>
#include<string.h>
#include<algorithm>
using namespace std;
const int maxn=1001;
char g[maxn][maxn];
int vis[maxn][maxn];
int tim[maxn][maxn];
const int inf=0x3f3f3f3f;
int n,m;
struct node{
	int x,y,t;
	node(int x_=0,int y_=0,int t_=0):x(x_),y(y_),t(t_){}
};
queue<node>F,J;
int dr[][2]={{-1,0},{1,0},{0,1},{0,-1}};

int ok(int xx,int yy){
	return (xx>=0&&yy>=0&&xx<n&&yy<m);
}

void bfs_F(void){
	while(!F.empty ()){
		node temp=F.front ();F.pop ();
		int x=temp.x;
		int y=temp.y;
		int t=temp.t;
		for(int i=0;i<4;i++){
			int xx=x+dr[i][0];
			int yy=y+dr[i][1];
			int tt=t+1;
			if(ok(xx,yy)){
				if((g[xx][yy]=='.'||g[xx][yy]=='J')&&tt<tim[xx][yy]){
					F.push (node(xx,yy,tt));
					tim[xx][yy]=tt;
				}
			}
		}
	}
}

int out(int x,int y){
	return (x==0||y==0||x==n-1||y==m-1);
}

int bfs_J(void){
	while(!J.empty ()){
		node temp=J.front ();J.pop ();
		if(out(temp.x,temp.y)){
			return temp.t+1;
		}
		for(int i=0;i<4;i++){
			int x=temp.x+dr[i][0];
			int y=temp.y+dr[i][1];
			int t=temp.t+1;
			if(ok(x,y)){
				if(g[x][y]=='.'&&!vis[x][y]&&t<tim[x][y]){
					J.push (node(x,y,t));
					vis[x][y]=1;
				}
			}
		}
	}
	return 0;
}

int main(){
	int t;
	scanf("%d",&t);
	while(t--){
		memset(tim,inf,sizeof(tim));
		while(!J.empty()){J.pop();}
		while(!F.empty()){F.pop();}
		memset(vis,0,sizeof(vis));
		scanf("%d%d",&n,&m);
		getchar();
		for(int i=0;i<n;i++){
			gets(g[i]);
			for(int j=0;j<m;j++){
				if(g[i][j]=='F'){
					F.push (node(i,j,0));
				}else if(g[i][j]=='J'){
					J.push (node(i,j,0));
					vis[i][j]=1;
				}
			}
		}
		bfs_F();
		if(int t=bfs_J()){
			printf("%d\n",t);
		}else{
			printf("IMPOSSIBLE\n");
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值