Description
一天, 一个画家在森林里写生,突然爆发了山洪,他需要尽快返回住所中,那里是安
全的。
森林的地图由R行C列组成,空白区域用点“.”表示,洪水的区域用“”表示,而
岩石用“X”表示,另画家的住所用“D”表示,画家用“S”表示。
有以下几点需要说明:
1、 每一分钟画家能向四个方向移动一格(上、下、左、右)
2、 每一分钟洪水能蔓延到四个方向的相邻格子(空白区域)
3、 洪水和画家都不能通过岩石区域
4、 画家不能通过洪水区域(同时也不行,即画家不能移到某个格子,该格子在画家达到的同时被洪水蔓延到了,这也是不允许的)
5、 洪水蔓不到画家的住所。
给你森林的地图,编写程序输出最少需要花费多长时间才能从开始的位置赶回家中。
Input
输入第一行包含两个整数R和C(R,C<=50)。
接下来R行每行包含C个字符(“.”、“”、“X”、“D”或“S”)。地图保证只有一个“D”和一个“S”。
Output
输出画家最快安全到达住所所需的时间,如果画家不可能安全回家则输出“KAKTUS”。
Sample Input
输入1:
3 3
D.*
…
.S.
输入2:
3 3
D.*
…
…S
输入3:
3 6
D…*.
.X.X…
…S.
Sample Output
输出1:
3
输出2:
KAKTUS
输出3:
6
Data Constraint
解析:两遍广搜,第一遍模拟洪水流到每个点的最少时间,第二遍模拟画家能不能回家,(注意可能有多个洪水)
#include <bits/stdc++.h>
using namespace std;
int c,r,x1[1001],len,y11[1001],x2,y2,mapp[1001][1001],tx,ty;
int fx[4][2]={{1,0},{-1,0},{0,-1},{0,1}};
bool p[101][101];
queue x,y;
void bfs1 ()
{
for (int i=1;i<=len;i++)
x.push(x1[i]),y.push(y11[i]),
p[x1[i]][y11[i]]=1;
while (!x.empty())
{
int hx=x.front(),hy=y.front();
x.pop();y.pop();
p[hx][hy]=0;
for (int i=0;i<4;i++)
{
tx=hx+fx[i][0];ty=hy+fx[i][1];
if (mapp[tx][ty]>mapp[hx][hy]+1&&tx>0&&tx<=r&&ty>0&&ty<=c)
{
mapp[tx][ty]=mapp[hx][hy]+1;
if (p[tx][ty]0)
x.push(tx),y.push(ty),p[tx][ty]=1;
}
}
}
}
bool bfs2 ()
{
while (!x.empty()) x.pop();
while (!y.empty()) y.pop();
memset (p,0,sizeof§);
x.push(x2);y.push(y2);
p[x2][y2]=1;
mapp[x2][y2]=0;
while (!x.empty())
{
int hx=x.front(),hy=y.front();
x.pop();y.pop();
for (int i=0;i<4;i++)
{
tx=hx+fx[i][0];ty=hy+fx[i][1];
if (mapp[tx][ty]-1)
{
mapp[tx][ty]=mapp[hx][hy]+1;return true;
}
if (mapp[tx][ty]>mapp[hx][hy]+1&&!p[tx][ty]&&tx>0&&tx<=r&&ty>0&&ty<=c)
{
mapp[tx][ty]=mapp[hx][hy]+1;
p[tx][ty]=1;
x.push(tx);y.push(ty);
}
}
}
return false;
}
int main()
{
cin>>r>>c;
string s;
for (int i=1;i<=r;i++)
{
cin>>s;
for (int j=1;j<=c;j++)
{
if (s[j-1]’.’) mapp[i][j]=1e9;
if(s[j-1]’*’) x1[++len]=i,y11[len]=j;
if (s[j-1]‘D’) mapp[i][j]=-1;
if (s[j-1]‘X’) mapp[i][j]=-2;
if (s[j-1]==‘S’) x2=i,y2=j;
}
}
bfs1 ();
if (bfs2 ())
cout<<mapp[tx][ty];
else cout<<“KAKTUS”;
}