JZOJ 1235. 洪水

题目

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

 

分析

 

  • bfs跑两遍

代码

 1 #include<iostream>
 2 #include<cstring> 
 3 #include<queue>
 4 using namespace std;
 5 int map[100][100];
 6 int wa[100][100],dis[100][100],flag[100][100];
 7 int fx[5][2]={{0,0},{0,1},{1,0},{-1,0},{0,-1}};
 8 int n,m,x1,y1,x2,y2;
 9 queue<int> q;
10 void bfs()
11 {
12     while (!q.empty())
13     {
14         int x=q.front(); q.pop(); int y=q.front(); q.pop();
15         for (int i=1;i<=4;i++)
16         {
17             int ax=x+fx[i][0],ay=y+fx[i][1];
18             if (ax<1||ax>n||ay<1||ay>m||map[ax][ay]||flag[ax][ay]) continue;
19             wa[ax][ay]=min(wa[x][y]+1,wa[ax][ay]);
20             q.push(ax); q.push(ay);
21             flag[ax][ay]=1;
22         }
23     }
24 }
25 void bbfs()
26 {
27     memset(dis,0x3f,sizeof(dis)); 
28     memset(flag,0,sizeof(flag));
29     while (!q.empty()) q.pop();
30     q.push(x1); q.push(y1); dis[x1][y1]=1;
31     while (!q.empty())
32     {
33         int x=q.front(); q.pop(); int y=q.front(); q.pop();
34         for (int i=1;i<=4;i++)
35         {
36             int ax=x+fx[i][0],ay=y+fx[i][1];
37             if (ax<1||ax>n||ay<1||ay>m||map[ax][ay]||flag[ax][ay]||wa[ax][ay]<=dis[x][y]+1) continue;
38             dis[ax][ay]=min(dis[x][y]+1,dis[ax][ay]);
39             q.push(ax); q.push(ay);
40             flag[ax][ay]=1;
41         }
42     }
43 }
44 int main ()
45 {
46     char c;
47     cin>>n>>m;
48     memset(wa,0x7f,sizeof(wa));
49     for (int i=1;i<=n;i++)
50     {
51         for (int j=1;j<=m;j++)
52         {
53             cin>>c;
54             if (c=='D') x2=i,y2=j;
55             else if (c=='S') x1=i,y1=j;
56             else if (c=='X') map[i][j]=1;
57             else if (c=='*') q.push(i),q.push(j),wa[i][j]=1,flag[i][j]=1;
58         }
59     }
60     map[x2][y2]=1;
61     bfs();
62     map[x2][y2]=0;
63     bbfs();
64     if (dis[x2][y2]!=1061109567) cout<<dis[x2][y2]-1;
65     else cout<<"KAKTUS";
66 }

猜你喜欢

转载自www.cnblogs.com/zjzjzj/p/11333040.html
今日推荐