主要思路:
- 用四邻域洪水覆盖算法(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| ∣x1−y1∣+∣x2−y2∣,也就是两者之间的曼哈顿距离。
奶牛很美,但是代码挺丑
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;
}