题目:P5198 [USACO19JAN]Icy Perimeter
搜索 - DFS - BFS
题目大意
给出一个由.
和#
组成的二维矩阵,每一个连通块都有一个面积 和 周长,求面积最大的连通块的面积和周长,若有多个面积一样大的,输出周长最小的那个
根据题意,我们需要求出每个连通块的面积和周长,面积就不用说了,难点在求周长
我们使用bfs,设当前出队的点为
x
x
x。在点
x
x
x向四周寻找遍历的下一个点
y
y
y时,若
y
y
y不是冰淇淋格或者在地图之外,说明点
x
,
y
x,y
x,y之间的缝隙是连通块的边缘,所以周长++
若冰淇淋含有洞,以上方法仍然适用
#include<cstdio>
#include<iostream>
#include<queue>
using namespace std;
const int Maxn=1010,inf=0x3f3f3f3f;
const int dx[]={1,-1,0,0},dy[]={0,0,-1,1};
bool a[Maxn][Maxn],vis[Maxn][Maxn];
int n,ans,tot=inf;
struct node{
int x,y;
node(int u,int v)
{
x=u,y=v;
}
};
inline int read()
{
int s=0,w=1;
char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
while(ch>='0' && ch<='9')s=(s<<3)+(s<<1)+(ch^48),ch=getchar();
return s*w;
}
bool check(int x,int y)
{
return x<1 || y<1 || x>n || y>n || a[x][y];
}
void bfs(int sx,int sy)
{
queue <node> q;
vis[sx][sy]=1;
int size=0,cir=0; // 维护面积和周长
q.push(node(sx,sy));
while(q.size())
{
int x=q.front().x,y=q.front().y;
q.pop();
size++;
for(int i=0;i<4;++i)
{
int u=x+dx[i],v=y+dy[i];
if(check(u,v)){cir++;continue;}
if(vis[u][v])continue;
vis[u][v]=1;
q.push(node(u,v));
}
}
if(size>ans || (size==ans) && cir<tot)
ans=size,tot=cir;
}
int main()
{
// freopen("in.txt","r",stdin);
// freopen("perimeter.in","r",stdin);
// freopen("perimeter.out","w",stdout);
n=read();
for(int i=1;i<=n;++i)
for(int j=1;j<=n;++j)
{
char ch;
cin>>ch;
if(ch=='.')a[i][j]=1;
else a[i][j]=0;
}
for(int i=1;i<=n;++i)
for(int j=1;j<=n;++j)
if(!vis[i][j] && !a[i][j])bfs(i,j);
printf("%d %d\n",ans,tot);
return 0;
}