城堡問題
# = Wall
| = No wall
- = No wall
圖1是一個城堡的地形圖。請你編寫一個程序,計算城堡一共有多少房間,最大的房間有多大。城堡被分割成mn(m≤50,n≤50)個方塊,每個方塊可以有0~4面牆。
input
程序從標準輸入設備讀入數據。第一行是兩個整數,分別是南北向、東西向的方塊數。在接下來的輸入行裏,每個方塊用一個數字(0≤p≤50)描述。用一個數字表示方塊周圍的牆,1表示西牆,2表示北牆,4表示東牆,8表示南牆。每個方塊用代表其周圍牆的數字之和表示。城堡的內牆被計算兩次,方塊(1,1)的南牆同時也是方塊(2,1)的北牆。輸入的數據保證城堡至少有兩個房間。
output
城堡的房間數、城堡中最大房間所包括的方塊數。結果顯示在標準輸出設備上。
樣例
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
#include<cstdio>
#include<cstring>
#include<iostream>
#define max(a,b) a>b?a:b//定義在頭文件中
using namespace std;
int map[51][51];
int color[51][51];//深搜染色
int max1,num=0,area;
void dfs(int i,int j)
{
if(color[i][j])//染色標記法
return;
area++;
color[i][j]=num;
if((map[i][j]&1)==0)dfs(i,j-1);//搜索西
if((map[i][j]&2)==0)dfs(i-1,j);// 北牆
if((map[i][j]&4)==0)dfs(i,j+1);// 東
if((map[i][j]&8)==0)dfs(i+1,j);// 南
}
int main()
{
int n,m;
while(scanf("%d%d",&n,&m)==2)//當兩個都成功輸入
{
num=0;
max1=0;
memset(color,0,sizeof(color));
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cin>>map[i][j];
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(!color[i][j])
{
area=0;//每次深搜到底又需要重新開始
num++;//這是記錄有幾個房間的,能進行幾次深搜,就有幾個房間
dfs(i,j);
max1=max(max1,area);//之前的與這次比較
}
}
}
cout<<num<<endl;
cout<<max1<<endl;
}
}