The Castle POJ - 1164

     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

题目大意:
n*m个方格组成的城堡,其中方格的每个墙都有一个值,西墙-1,东墙-4,北墙-2,南墙-8;

输入N*M个数字(为每个方格所包含墙的值之和),分别表示每个方格的墙的的情况。

问这个城堡共有多少个房间,其中最大的房间所包含的方格数是多少?

解题思路:

dfs搜索,不难发现,当方格没有南墙时,其对应的值一定小于8,这样就可以向下继续搜索了,当有南墙时,其值大于8

先让其值对8取余再赋给它(这样就可以避免南墙的干扰),然后判断是否有东墙,如何判断呢?仍然是求余有东墙,看求余的值与4比较,如果比4大,说明有东墙,否则没有,可以发现;如果对4求余,并不能保证可以判断出是否有东墙,例如,9%4=1<4,12%4=0<4;当两个例子一个有东墙,一个没有。所以不能对4求余。对8呢?可以区分,9%8=1<4;12%8=4不小于4;

然后在对4取余在赋给它自己;依次类推,判断是否有北墙对4在求余看是否小于2,当大于2时,表示有北墙,在对2取余,然后对2取余判断是否小于1.

代码:

#include
#include
#include
using namespace std;
int a[55][55];
int b[55][55];
int sum=0,maxx=0,ans=0;

void dfs(int x,int y)
{
    if(b[x][y]==1)
        return ;
    b[x][y]=1;
    ans++;
    if(a[x][y]<8)
        dfs(x+1,y);

    a[x][y]%=8;
    if(a[x][y]<4)
    {
        dfs(x,y+1);
    }

    a[x][y]%=4;
    if(a[x][y]<2)
    {
        dfs(x-1,y);
    }
    a[x][y]%=2;

    if(a[x][y]<1)
    {
        dfs(x,y-1);
    }

}

int main()
{
    int n,m;
    cin>>n>>m;
    memset(b,0,sizeof(b));
    for(int i=0;ifor(int j=0;jscanf("%d",&a[i][j]);
        }
    }
    for(int i=0;ifor(int j=0;j0;
            if(b[i][j]==0)
            {
                dfs(i,j);
                sum++;
            }
            if(ans>maxx)
                maxx=ans;
        }
    }
    cout<cout<

你可能感兴趣的:(模拟,搜索)