ybt1250 The Castle
时空限制 1000ms/64MB
【题目描述】
一座城堡被分成m*n个方块(m≤50,n≤50),每个方块可有0~4堵墙(0表示无墙)。下面示出了建筑平面图:
图中的加粗黑线代表墙。几个连通的方块组成房间,房间与房间之间一定是用黑线(墙)隔开的。
现在要求你编一个程序,解决以下2个问题:
1、该城堡中有多少个房间?
2、最大的房间有多大?
【输入】
平面图用一个数字表示一个方块(第1个房间用二进制1011表示,0表示无东墙,用十进制11表示)。
第一行一个整数m(m≤50),表示房子南北方向的长度。
第二行一个整数n(n≤50),表示房子东西方向的长度。
后面的m行,每行有n个整数,每个整数都表示平面图对应位置的方块的特征。每个方块中墙的特征由数字P来描述(0≤P≤15)。数字P是下面的可能取的数字之和:
1(西墙 west)
2(北墙 north)
4(东墙 east)
8(南墙 south)
室内的墙被定义两次: 例如方块(1,1)中的南墙也被位于其南面的方块(2,1)定义了一次。
建筑中至少有两个房间。
【输出】
第1行:一个整数,表示房间总数;
第2行:一个整数,表示最大房间的面积(方块数)。
【输入样例】
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
代码
法一:STL队列
#include<iostream>
#include<queue>
#include<algorithm>
using namespace std;
const int N = 55;
const int dx[] = { 0,-1, 0, 1},
dy[] = {-1, 0, 1, 0},
fx[] = { 1, 2, 4, 8};
int m,n,g[N][N],tot,cnt,maxx;
bool visit[N][N];
struct node{
int x,y;
node(){ }
node(int a,int b):x(a),y(b){ }
};
queue<node> q;
void bfs(int x,int y){
tot++; cnt=1;
q.push(node(x,y));
visit[x][y] = true;
while (!q.empty()){
node k=q.front(); q.pop();
for (int i=0; i<4; i++){
x=k.x+dx[i]; y=k.y+dy[i];
if (x>=1 && x<=m && y>=1 && y<=n && !visit[x][y] && (g[k.x][k.y]&fx[i])==0){
cnt++; //房间面积+1
q.push(node(x,y));
visit[x][y] = true;
}
}
}
maxx = max(maxx,cnt); //找最大房间面积
}
int main(){
cin>>m>>n;
for (int i=1; i<=m; i++)
for (int j=1; j<=n; j++) cin>>g[i][j];
for (int i=1; i<=m; i++)
for (int j=1; j<=n; j++)
if (!visit[i][j]) bfs(i,j);
cout<<tot<<endl<<maxx<<endl;
return 0;
}
法二:手动队列
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 55;
const int dx[] = { 0,-1, 0, 1},
dy[] = {-1, 0, 1, 0},
fx[] = { 1, 2, 4, 8};
int m,n,g[N][N],tot,cnt,maxx;
int que[N*N][2],head,tail;
bool visit[N][N];
void bfs(int x,int y){
tot++; cnt=1;
head=0; tail=0;
que[++tail][0]=x; que[tail][1]=y;
visit[x][y] = true;
while (head<tail){
head++;
int x0=que[head][0],y0=que[head][1]; //队头坐标
for (int i=0; i<4; i++){
x=x0+dx[i]; y=y0+dy[i];
if (x>=1 && x<=m && y>=1 && y<=n && !visit[x][y] && (g[x0][y0]&fx[i])==0){
cnt++; //房间面积+1
que[++tail][0]=x; que[tail][1]=y;
visit[x][y] = true;
}
}
}
maxx = max(maxx,cnt); //找最大房间面积
}
int main(){
cin>>m>>n;
for (int i=1; i<=m; i++)
for (int j=1; j<=n; j++) cin>>g[i][j];
for (int i=1; i<=m; i++)
for (int j=1; j<=n; j++)
if (!visit[i][j]) bfs(i,j);
cout<<tot<<endl<<maxx<<endl;
return 0;
}