AcWing 2060. 奶牛选美
原题链接
中等
c ++
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
const int N = 55;
typedef pair<int, int> PII;
char g[N][N];
int res = 0x3f3f3f3f;
vector<PII> ltk[2];
int n, m;
void dfs(int x, int y, vector<PII>& ps)
{
g[x][y] = '.';
ps.push_back({x, y});
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
for (int i = 0; i < 4; i ++ )
{
int a = x + dx[i], b = y + dy[i];
if(a >= 0 && a < n && b >= 0 && b < m && g[a][b] == 'X')
dfs(a, b, ps);
}
}
int main()
{
cin >> n >> m;
for (int i = 0; i < n; i ++ ) cin >> g[i];
for (int i = 0, k = 0; i < n; i ++ )
for (int j = 0; j < m; j ++ )
if(g[i][j] == 'X')
dfs(i, j, ltk[k ++ ]);
for(auto t : ltk[0])
for(auto t2 : ltk[1])
res = min(res, abs(t.first - t2.first) + abs(t.second - t2.second) - 1);
cout << res;
return 0;
}