P5198 [USACO19JAN]Icy Perimeter 题解

题目: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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值