链接:https://ac.nowcoder.com/acm/problem/14340
来源:牛客网
时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 32768K,其他语言65536K
64bit IO Format: %lld
题目描述
这是mengxiang000和Tabris来到幼儿园的第四天,幼儿园老师在值班的时候突然发现幼儿园某处发生火灾,而且火势蔓延极快,老师在第一时间就发出了警报,位于幼儿园某处的mengxiang000和Tabris听到了火灾警报声的同时拔腿就跑,不知道两人是否能够逃脱险境?
幼儿园可以看成是一个N*M的图,在图中一共包含以下几种元素:
“.”:表示这是一块空地,是可以随意穿梭的。
“#”:表示这是一块墙,是不可以走到这上边来的,但是可以被火烧毁。
“S”:表示mengxiang000和Tabris所在位子。
“E”:表示幼儿园的出口。
“*”表示火灾发源地(保证输入只有一个火灾发源地)。
已知每秒有火的地方都会向周围八个格子(上下左右、左上、右上、左下、右下)蔓延火势.mengxiang000和Tabris每秒都可以选择周围四个格子(上下左右)进行移动。(假设两人这一秒行动完之后,火势才蔓延开)
根据已知条件,判断两人能否成功逃脱险境,如果可以,输出最短逃离时间,否则输出T_T。
输入描述:
第一行输入一个整数t,表示一共的测试数据组数。 第二行输入两个整数n,m,表示幼儿园的大小。 接下来n行,每行m个字符,表示此格子是什么元素。 t<=200 3<=n<=30 3<=M<=30 保证图中有一个起点,一个出口,一个火灾源处.
输出描述:
每组数据输出一行,如果两人能够成功到达出口,那么输出最短逃离时间,否则输出T_T
输入
3 5 5 *.... ..... ..S#. ...E. ..... 5 5 ...#* ..#S# ...## ....E ..... 5 5 ..... S.... ..*#. ...E. .....
输出
2 T_T T_T
备注:
为了防止孩子们嬉戏中受伤,墙体是橡胶制作的,可以燃烧的哦。
思路:先跑一遍BFS,找出火势蔓延到每个方格的时间,然后跑BFS的时候加上时间的判断
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <string>
#include <cstdio>
#include <vector>
#include <cmath>
#include <queue>
#include <deque>
#include <stack>
#include <map>
#include <set>
#define eps 0.0000000001
#define mem(a) memset(a,0,sizeof(a))
#define MAX 1e9
#define inf 99999999999999999
#define mod 1000000007
using namespace std;
typedef long long ll;
//priority_queue<int,vector<int>,greater<int> > q;
#define mod 1000000007
const ll N=10000005;
struct A
{
int x,y;
int time;
}start,now,t;
int n,m,sx,sy,hx,hy;
char a[35][35];
int vis[35][35],h[35][35];
int dir1[8][2]={0,1,0,-1,1,0,-1,0,1,1,1,-1,-1,1,-1,-1};
int dir2[4][2]={0,1,0,-1,1,0,-1,0};
void BFS1()
{
mem(vis);
queue<A> q;
start.x=hx;
start.y=hy;
start.time=0;
q.push(start);
vis[start.x][start.y]=1;
h[start.x][start.y]=0;
while(!q.empty())
{
now=q.front();
q.pop();
for(int i=0;i<8;i++)
{
A t;
int xx=now.x+dir1[i][0];
int yy=now.y+dir1[i][1];
t.x=xx;
t.y=yy;
t.time=now.time+1;
if(xx>=1&&xx<=n&&yy>=1&&yy<=m&&vis[xx][yy]==0)
{
q.push(t);
vis[xx][yy]=1;
if(a[xx][yy]!='E')
h[xx][yy]=t.time;
else
h[xx][yy]=t.time+1;
}
}
}
return;
}
int BFS2()
{
queue<A> q;
mem(vis);
start.x=sx;
start.y=sy;
start.time=0;
q.push(start);
vis[start.x][start.y]=1;
while(!q.empty())
{
now=q.front();
q.pop();
if(a[now.x][now.y]=='E')
{
return now.time;
}
for(int i=0;i<4;i++)
{
A t;
t.x=now.x+dir2[i][0];
t.y=now.y+dir2[i][1];
t.time=now.time+1;
if(t.x>=1&&t.x<=n&&t.y>=1&&t.y<=m&&vis[t.x][t.y]==0)
if(t.time<h[t.x][t.y]&&a[t.x][t.y]!='#')
{
q.push(t);
vis[t.x][t.y]=1;
}
}
}
return -1;
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
{
getchar();
for(int j=1;j<=m;j++)
{
scanf("%c",&a[i][j]);
if(a[i][j]=='S')
{
sx=i;
sy=j;
}
if(a[i][j]=='*')
{
hx=i;
hy=j;
}
}
}
BFS1();
int ans=BFS2();
if(ans==-1)
cout<<"T_T"<<endl;
else
cout<<ans<<endl;
}
return 0;
}