百练(2815):城堡问题(DFS)

总时间限制: 

1000ms

内存限制: 

65536kB

描述

     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

来源

1164

解题思路:

对每一个房间,深度优先搜索,从而给这个房间能够到达的所有位置染色。最后统计一共用了几种颜色,以及每种颜色的数量。

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

const int maxn = 50+5;
int room[maxn][maxn];
int color[maxn][maxn];
int RoomNum = 0;
int RoomArea,MaxRoomArea = 0;

void DFS(int i,int k){
    if(color[i][k])
        return;
    color[i][k] = RoomNum;
    RoomArea++;
    if( (room[i][k] & 1) == 0 ) DFS(i,k-1);  //按位与,东西南北都是2的n次方,并且给定的格子是墙对应数字和,很容易想到用二进制表示有没有墙
    if( (room[i][k] & 2) == 0 ) DFS(i-1,k);
    if( (room[i][k] & 4) == 0 ) DFS(i,k+1);
    if( (room[i][k] & 8) == 0 ) DFS(i+1,k);
}
int main()
{
    int r,c;
    scanf("%d%d",&r,&c);
    for(int i = 1;i <= r;i++)
        for(int j = 1;j <= c;j++){
            scanf("%d",&room[i][j]);
    }
    memset(color,0,sizeof(color));
    for(int i = 1;i <= r;i++){
        for(int j = 1;j <= c;j++){
            if(!color[i][j]){ //遍历每一个没有被染色的方块
                RoomNum++;
                RoomArea = 0;
                DFS(i,j);
                MaxRoomArea = max(MaxRoomArea,RoomArea);
            }
        }
    }
    printf("%d\n",RoomNum);
    printf("%d",MaxRoomArea);
}

猜你喜欢

转载自blog.csdn.net/qq_42018521/article/details/81701231