开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 21 天,点击查看活动详情
题目
1 2 3 4 5 6 7
#############################
1 # | # | # | | #
#####---#####---#---#####---#
2 # # | # # # # #
#---#####---#####---#####---#
3 # | | # # # # #
#---#########---#####---#---#
4 # # | | | | # #
#############################
(图 1)
# = Wall
| = No wall
- = No wall
方向:上北下南左西右东。
图1是一个城堡的地形图。
请你编写一个程序,计算城堡一共有多少房间,最大的房间有多大。
城堡被分割成 m∗n�∗�个方格区域,每个方格区域可以有0~4面墙。
注意:墙体厚度忽略不计。
输入格式
第一行包含两个整数 m� 和 n�,分别表示城堡南北方向的长度和东西方向的长度。
接下来 m� 行,每行包含 n� 个整数,每个整数都表示平面图对应位置的方块的墙的特征。
每个方块中墙的特征由数字 P� 来描述,我们用1表示西墙,2表示北墙,4表示东墙,8表示南墙,P� 为该方块包含墙的数字之和。
例如,如果一个方块的 P� 为3,则 3 = 1 + 2,该方块包含西墙和北墙。
城堡的内墙被计算两次,方块(1,1)的南墙同时也是方块(2,1)的北墙。
输入的数据保证城堡至少有两个房间。
输出格式
共两行,第一行输出房间总数,第二行输出最大房间的面积(方块数)。
数据范围
1≤m,n≤501≤�,�≤50,
0≤P≤150≤�≤15
输入样例:
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
分析
这题是一个很睿智的bfs,flood-fill模板,但是有一点要注意,就是方向数组。
代码
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <vector>
#include <map>
#include <set>
#include <iomanip>
#include <cmath>
#include <unordered_map>
#include <stack>
#include <queue>
#define ll long long
#define lowbit(x) x&(-x)
using namespace std;
typedef pair<int,ll> PII;
typedef pair<string,int> PSI;
typedef stack<int> stk;
ll gcd(ll x,ll y){
return y?gcd(y,x%y):x;
}
ll qmi(ll x,ll y,int mod){
ll res=1;
while(y){if(y&1) res=res*x%mod;y>>=1;x=x*x%mod;}
return res;
}
const int N=55;
int g[N][N],n,m,cnt=0,maxn=0;
bool st[N][N];
int dx[4]={0,-1,0,1};
int dy[4]={-1,0,1,0};
int bfs(int x,int y){
st[x][y]=true;
queue<PII> q;
q.push({x,y});
int area=0;
while(q.size()){
PII t=q.front();
area++;
q.pop();
int nowx=t.first,nowy=t.second;
for(int i=0;i<4;i++){
int nex=nowx+dx[i],ney=nowy+dy[i];
if(nex>=1 && nex<=n && ney>=1 && ney<=m && !st[nex][ney] && (g[nowx][nowy]>>i&1)==0){
//area++;
st[nex][ney]=true;
q.push({nex,ney});
}
}
}
return area;
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0),cout.tie(0);
cin>>n>>m;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cin>>g[i][j];
}
}
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
if(!st[i][j]){
//cout<<bfs(i,j)<<"\n";
maxn=max(maxn,bfs(i,j));
cnt++;
}
}
}
cout<<cnt<<"\n"<<maxn<<"\n";
return 0;
}
希望能帮助到大家QAQ!