uva 11624 Fire!

在這裏插入圖片描述
在這裏插入圖片描述
先bfs火,存儲火的位置及時間的關係,放入隊列,再bfs人

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string>
#include<string.h>
#include<cstring>
#include<queue>
#include<vector>
using namespace std;
int t;
int r,c;//行,列
char mp[1005][1005];//地圖
int per[1005][1005];//人
int fire[1005][1005];//火
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
queue<pair<int ,int>> que;
int check_fire(int x,int y)
{
	if(x<0||x>=r||y<0||y>=c)//超出地圖範圍
		return 1;
	if(fire[x][y]!=-1)//已經被燒過
		return 1;
	if(mp[x][y]=='#')//是牆
		return 1;
	return 0;
}
int check_person(int x,int y,int xx,int yy)
{
	if(xx<0||xx>=r||yy<0||yy>=c)//超出地圖範圍
		return 1;
	if(per[x][y]+1>=fire[xx][yy]&&fire[xx][yy]!=-1)//人到的時候火已經到了,注意這裏per[xx][yy]還沒有計算不能使用,要用per[x][y]代替
		return 1;
	if(per[xx][yy]!=-1)//走過
		return -1;
	if(mp[xx][yy]=='#')//是牆
		return 1;
	return 0;
}
void bfs_fire()
{
	for(int i=0;i<r;i++)
		for(int j=0;j<c;j++)
		{
			if(mp[i][j]=='F')
			{
				fire[i][j]=0;//一開始火燃燒的時間爲0
				que.push(make_pair(i,j));
			}
		}
	while(!que.empty())
	{
		pair<int,int> pa;
		pa=que.front();
		que.pop();
		int x=pa.first;
		int y=pa.second;
		for(int i=0;i<4;i++)
		{
			int xx=x+dir[i][0];
			int yy=y+dir[i][1];
			if(check_fire(xx,yy))
				continue;
			fire[xx][yy]=fire[x][y]+1;//燃燒時間加一
			que.push(make_pair(xx,yy));
		}
	}
}
int bfs_person()
{
	for(int i=0;i<r;i++)
		for(int j=0;j<c;j++)
		{
			if(mp[i][j]=='J')
			{
				per[i][j]=0;//一開始人走的時間爲0
				que.push(make_pair(i,j));
			}
		}
	while(!que.empty())
	{
		pair<int,int> p;
		p=que.front();
		que.pop();
		int px=p.first;
		int py=p.second;
		if(px==0||py==0||px==r-1||py==c-1)//如果到達邊界(這裏不會出現人在邊界火也在邊界的情況,因爲後面已經排除了)
			return per[px][py]+1;//返回所用時間加一
		for(int i=0;i<4;i++)
		{
			int pxx=px+dir[i][0];
			int pyy=py+dir[i][1];
			if(check_person(px,py,pxx,pyy))
				continue;
			per[pxx][pyy]=per[px][py]+1;
			que.push(make_pair(pxx,pyy));
		}
	}
	return -1;
}
int main()
{
	scanf("%d",&t);
	while(t--)
	{
		memset(fire,-1,sizeof(fire));
		memset(per,-1,sizeof(per));
		memset(mp,0,sizeof(mp));
		while(!que.empty())
		{
			que.pop();
		}
		scanf("%d%d",&r,&c);
		getchar();
		for(int i=0;i<r;i++)
		{
			for(int j=0;j<c;j++)
			{
				scanf("%c",&mp[i][j]);
			}
			getchar();
		}
		bfs_fire();
		int ans=bfs_person();
		if(ans==-1)
			printf("IMPOSSIBLE\n");
		else
			printf("%d\n",ans);
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章