acwing 2060 奶牛选美 | vegeone
0%

acwing 2060 奶牛选美

题意

给定一张二维图,图上有两个连通块,求使得两个连通块相连的最短路径。

思路

由于无法区分两个连通块,所以通过dfs对两个连通块中的元素分别赋值0/1,然后对于两个连通块中的所有点分别求曼哈顿距离-1即可。(曼哈顿距离:水平距离+竖直距离)

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include<bits/stdc++.h>
#define int long long
using namespace std;
#define endl '\n'
const int N=1e5+10;
typedef pair<int,int>pp;
int d[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
void solve()
{
int n,m;
cin>>n>>m;
vector<string>vec(n);
for(int i=0;i<n;++i){
cin>>vec[i];
}
auto check=[&](int x,int y){
if(x<0||x>=n||y<0||y>=m||vec[x][y]=='.')return false;
else return true;
};
vector<vector<int> > vis(n,vector<int>(m));
vector<vector<pp>>ans(2);
auto dfs=[&](auto dfs,int x,int y,int cnt){

if(vis[x][y])return;
ans[cnt].push_back({x,y});
vec[x][y]='0'+cnt;
vis[x][y]=1;
for(int i=0;i<4;++i){
int sx=x+d[i][0],sy=y+d[i][1];
if(!check(sx,sy))continue;
dfs(dfs,sx,sy,cnt);
}
};
int cnt=0;
for(int i=0;i<n;++i){
for(int j=0;j<m;++j){
if(vec[i][j]=='X'){
for(int i=0;i<n;++i){
for(int j=0;j<m;++j){
vis[i][j]=0;
}
}
dfs(dfs,i,j,cnt);
++cnt;
}
}
}
int res=1e9;
for(auto tx:ans[0]){
for(auto ty:ans[1]){
res=min(res,abs(ty.second-tx.second)+abs(ty.first-tx.first)-1);
}
}
cout<<res<<endl;
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int T=1;
// cin>>T;
while(T--) solve();
return 0;
}