您的位置:首页 > 其它

城堡问题 ------ 深度优先搜索

2014-06-09 16:17 337 查看
总Time Limit: 1000ms Memory Limit: 65536kB

Description
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面墙。

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

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

Source

代码:

#include <iostream>

#include <cstdio>

#include <cstring>

using namespace std;

int R,C; //用于存储行和列

int rooms[60][60];

int color[60][60]; //存储房间是否被染色标记过

int maxRoomArea=0,roomNum=0; //最大房间的方块数,和一共有多少个房间

int roomArea;

void Dfs(int i,int k)

{

if(color[i][k])

return;

++roomArea;

color[i][k]=roomNum;

if((rooms[i][k]&&1)==0)
//向西走

Dfs(i,k-1);

if((rooms[i][k]&&2)==0)
//向北走

Dfs(i-1,k);

if((rooms[i][k]&&4)==0)
//向东走

Dfs(i,k+1);

if((rooms[i][k]&&8)==0)
//向南走

Dfs(i+1,k);

}

int main()

{

cin>>R>>C;

for(int i=1;i<=R;++i)

{

for(int k=1;k<=C;++k)

{

cin>>rooms[i][k];

}

}

memset(color,0,sizeof(color));

for(int i=1;i<=R;++i)

for(int k=1;k<=C;++k)

{

if(!color[i][k])

{

++roomNum;

roomArea=0;

Dfs(i,k);

maxRoomArea=max(roomArea,maxRoomArea);

}

}

cout<<roomNum<<endl;

cout<<maxRoomArea<<endl;

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: