The Castle(DFS)

版权声明:转载请注明出处链接 https://blog.csdn.net/qq_43408238/article/details/89457129
Total Submissions: 8387   Accepted: 4728

Description

     1   2   3   4   5   6   7  

   #############################

 1 #   |   #   |   #   |   |   #

   #####---#####---#---#####---#

 2 #   #   |   #   #   #   #   #

   #---#####---#####---#####---#

 3 #   |   |   #   #   #   #   #

   #---#########---#####---#---#

 4 #   #   |   |   |   |   #   #

   #############################

(Figure 1)



#  = Wall   

|  = No wall

-  = No wall


Figure 1 shows the map of a castle.Write a program that calculates
1. how many rooms the castle has
2. how big the largest room is
The castle is divided into m * n (m<=50, n<=50) square modules. Each such module can have between zero and four walls.

Input

Your program is to read from standard input. The first line contains the number of modules in the north-south direction and the number of modules in the east-west direction. In the following lines each module is described by a number (0 <= p <= 15). This number is the sum of: 1 (= wall to the west), 2 (= wall to the north), 4 (= wall to the east), 8 (= wall to the south). Inner walls are defined twice; a wall to the south in module 1,1 is also indicated as a wall to the north in module 2,1. The castle always has at least two rooms.

Output

Your program is to write to standard output: First the number of rooms, then the area of the largest room (counted in modules).

Sample Input

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

Sample Output

5
9

这个题目给出墙的状态已经状态压缩了,我们应该对二进制数感到敏感,1,2,4,8,不就是0001,0010,0100,1000。这样位运算判定通路就可以了,然后一个vis数组来标记走过的路。

#include<iostream>
#include<vector>
#include<string>
#include<cstring>
#include<cmath>
#include <algorithm>
#include <stdlib.h>
#include <cstdio>
#include<sstream>
#include<cctype>
#include <set>
#include<queue>
#include <map>
#include <iomanip>
#define  INF  0x3f3f3f3f
typedef long long ll;
const ll MAX=1000000;
using namespace std;
ll n,m,Maxarea,num,sum;
ll ans[60][60];//存放状态
bool vis[60][60];//记录走过的节点
void dfs(ll x,ll y)
{
     if(vis[x][y]) return ;//如果是旧点,退出
        num++;//新点面积加1
     vis[x][y]=1;//标记为旧点
    if(!(ans[x][y]&1) )  dfs(x,y-1);//判定通路
    if(!((ans[x][y]>>1)&1)) dfs(x-1,y);
    if(!((ans[x][y]>>2)&1)) dfs(x,y+1);
    if(!((ans[x][y]>>3)&1))  dfs(x+1,y);
}
int main()
{
    cin>>n>>m;
    for(ll i=1;i<=n;i++)
      for(ll j=1;j<=m;j++)
      cin>>ans[i][j];
      memset(vis,0,sizeof(vis));
      for(ll i=1;i<=n;i++)
          for(ll j=1;j<=m;j++)
           if(!vis[i][j])
           {

                ++sum;
                num=0;
                dfs(i,j);
              Maxarea=max(num,Maxarea);

           }
           cout<<sum<<endl<<Maxarea;
}

猜你喜欢

转载自blog.csdn.net/qq_43408238/article/details/89457129