百练2815:城堡问题(DFS)

描述


1 2 3 4 5 6 7
#############################
1 # | # | # | | #
#####---#####---#---#####---#
2 # # | # # # # #
#---#####---#####---#####---#
3 # | | # # # # #
#---#########---#####---#---#
4 # # | | | | # #
#############################
(图 1)

# = Wall
| = No wall
- = No wall


图1是一个城堡的地形图。请你编写一个程序,计算城堡一共有多少房间,最大的房间有多大。城堡被分割成mn(m≤50,n≤50)个方块,每个方块可以有0~4面墙。
输入程序从标准输入设备读入数据。第一行是两个整数,分别是南北向、东西向的方块数。在接下来的输入行里,每个方块用一个数字(0≤p≤50)描述。用一个数字表示方块周围的墙,1表示西墙,2表示北墙,4表示东墙,8表示南墙。每个方块用代表其周围墙的数字之和表示。城堡的内墙被计算两次,方块(1,1)的南墙同时也是方块(2,1)的北墙。输入的数据保证城堡至少有两个房间。输出城堡的房间数、城堡中最大房间所包括的方块数。结果显示在标准输出设备上。
样例输入

4 
7 
11 6 11 6 3 10 6 
7 9 6 13 5 15 5 
1 10 12 7 13 7 5 
13 11 10 8 10 12 13 

样例输出

5
9
 1 #include<iostream>
 2 #include<cstring>
 3 #include<algorithm>
 4 #include<cstdio>
 5 using namespace std;
 6 int n, m;//行数,列数
 7 int room[51][51];//保存房间信息
 8 int color[51][51];//标记数组,用来检查一个房间是否已经走过
 9 int roomNum = 0, maxArea = 0;//总的房间数和最大房间面积
10 int area = 0;//当前正在走的房间的面积
11 void dfs(int i,int j)//对当前位置做dfs,会得到该房间所在的联通分量
12 {
13     //cout << "dfs(" << i << "," << j << ")" << endl;
14     if (color[i][j])//为旧点
15     {
16         //cout << "(" << i << "," << j << ")是旧点" << endl;
17         return;
18     }
19     //cout << "(" << i << "," << j << ")不是旧点" << endl;
20     area++;
21     //标记为旧点
22     color[i][j] = roomNum;
23     //按西北东南的顺序做dfs,本题不用考虑边界问题,因为输入保证了四周都有墙,dfs一定会在到达边界的时候停下来
24     if (!(room[i][j] & 1))//西边没有墙往西走
25     {
26         //cout << "(" << i << "," << j << ")西边没有墙往西走" << endl;
27         dfs(i, j - 1);
28     }
29 
30     if (!(room[i][j] & 2))//北边没有墙往北走
31     {
32         //cout << "(" << i << "," << j << ")北边没有墙往北走" << endl;
33         dfs(i - 1, j);
34     }
35 
36     if (!(room[i][j] & 4))//东边没有墙往东走
37     {
38         //cout << "(" << i << "," << j << ")东边没有墙往东走" << endl;
39         dfs(i, j + 1);
40     }
41 
42     if (!(room[i][j] & 8))//南边没有墙往南走
43     {
44         //cout << "(" << i << "," << j << ")南边没有墙往南走" << endl;
45         dfs(i + 1, j);
46     }
47 
48 }
49 int main()
50 {
51     cin >> n >> m;
52     memset(room,0,sizeof(room));
53     memset(color, 0, sizeof(color));
54     for (int i = 1; i <= n; ++i)
55         for (int j = 1; j <= m; ++j)
56             cin >> room[i][j];
57 
58     for (int i = 1; i <= n; ++i)
59         for (int j = 1; j <= m; ++j)
60         {
61             if (!color[i][j])//这个房间没有被走过
62             {
63                 roomNum++;
64                 area = 0;
65                 dfs(i,j);
66                 maxArea = max(maxArea,area);
67             }
68         }
69     cout << roomNum  << endl;
70     cout << maxArea  << endl;
71     return 0;
72 }

 

posted @ 2018-08-28 11:05  敲代码不BB  阅读(195)  评论(0编辑  收藏  举报