数据范围小,直接暴力枚举两块斑点中每一个点,最后求出最小值即可。
#include <bits/stdc++.h>
using namespace std;
const int N = 60;
const int dr[] = { -1, 0, 1, 0 }, dc[] = { 0, 1, 0, -1 };
int n, m, st[N][N];
char g[N][N];
vector< pair<int, int> > block[2];
void dfs (vector< pair<int, int> > & block, int x, int y) {
st[x][y] = 1;
block.push_back(make_pair(x, y));
for (int i = 0; i < 4; i++) {
int dx = x + dr[i], dy = y + dc[i];
if (st[dx][dy] || dx < 1 || dx > n || dy < 1 || dy > m || g[dx][dy] != 'X') continue;
dfs(block, dx, dy);
}
}
int main () {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) cin >> (g[i] + 1);
for (int i = 1, which = 0;i <= n; i++ )
for (int j = 1; j <= m; j++)
if (!st[i][j] && g[i][j] == 'X') dfs(block[which++], i, j);
int dist = 1e9 + 10;
for (pair<int, int> & a : block[0])
for (pair<int, int> & b : block[1])
dist = min(abs(a.first - b.first) + abs(a.second - b.second), dist);
printf("%d", dist - 1);
return 0;
}