【蓝桥杯每日一题】3.15 奶牛选美

原题链接:2060. 奶牛选美 - AcWing题库

主要思路:

  • 用四邻域洪水覆盖算法(Flood Fill)找出找到“奶牛身上两块斑点”,也即是两个集合——两个连通图,时间复杂度为: O ( m n ) O(mn) O(mn)
  • 从字符集中筛选出两个集合,在两个集合中各找一个点,求两点之间的最短曼哈顿距离

何为曼哈顿距离?

  • 假设距离最短的路线的两个端点分别是 ( x 1 , y 1 ) (x1,y1) (x1,y1) ( x 2 , y 2 ) (x2,y2) (x2,y2),那么最短距离就等于 ∣ x 1 − y 1 ∣ + ∣ x 2 − y 2 ∣ |x1−y1|+|x2−y2| x1y1∣+x2y2∣,也就是两者之间的曼哈顿距离。

奶牛很美,但是代码挺丑

BFS代码:

奶牛选美,Flood Fill算法+曼哈顿距离,BFS
#include<bits/stdc++.h>
using namespace std;

typedef pair<int,int> PII;
const int N=55;

int n,m;
char g[N][N];
bool s[N][N];

void bfs(int x,int y,vector<PII> &points)
{
	int dx[4]={-1,0,1,0},dy[4]={0,-1,0,1};
	queue<PII> q;
	q.push({x,y});
	s[x][y]=true;
	
	while(q.size())
	{
		PII t=q.front();q.pop();
		points.push_back(t);
		
		for(int i=0;i<4;i++)
		{
			int nx=t.first+dx[i],ny=t.second+dy[i];
			//边界判断
			if(nx<0||nx>=n||ny<0||ny>=m) continue;
			if(g[nx][ny]=='.') continue;
			if(s[nx][ny]) continue;
			
			q.push({nx,ny});
			s[nx][ny]=true;
		}
	}
}

int main()
{
	scanf("%d%d",&n,&m);
	
	for(int i=0;i<n;i++) cin>>g[i];
	
	vector<PII> points[2];
	
	for(int i=0,k=0;i<n;i++)
	{
		for(int j=0;j<m;j++)
		{
			if(g[i][j]=='X'&&!s[i][j])
			{
				bfs(i,j,points[k++]);
			}	
		}	
	}
	
	int ans=1e6;
	for(auto &x:points[0])
	{
		for(auto &y:points[1])
		{
			ans=min(ans,abs(x.first-y.first)+abs(x.second-y.second));
		}
	}
	
	printf("%d",ans-1);
	return 0;
}

DFS代码:

#include<bits/stdc++.h>
using namespace std;

typedef pair<int,int> PII;
const int N=55;

int n,m;
char g[N][N];
bool s[N][N];

void dfs(int x,int y,vector<PII> &points)
{
	int dx[4]={-1,0,1,0},dy[4]={0,-1,0,1};
	
	s[x][y]=true;
	points.push_back({x,y});
	
	for(int i=0;i<4;i++)
	{
		int nx=x+dx[i],ny=y+dy[i];
		//边界判断	
		if(nx<0||nx>=n||ny<0||ny>=m) continue;
		if(g[nx][ny]=='.') continue;
		if(s[nx][ny]) continue;
			
		dfs(nx,ny,points);
	}	


}

int main()
{
	scanf("%d%d",&n,&m);
	
	for(int i=0;i<n;i++) cin>>g[i];
	
	vector<PII> points[2];
	
	for(int i=0,k=0;i<n;i++)
	{
		for(int j=0;j<m;j++)
		{
			if(g[i][j]=='X'&&!s[i][j])
			{
				dfs(i,j,points[k++]);
			}	
		}	
	}
	
	int ans=1e6;
	for(auto &x:points[0])
	{
		for(auto &y:points[1])
		{
			ans=min(ans,abs(x.first-y.first)+abs(x.second-y.second));
		}
	}
	
	printf("%d",ans-1);
	return 0;
}
  • 15
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值