提交时间:2022-08-09 11:32:55
运行 ID: 55118
#include <bits/stdc++.h> using namespace std; const int dx[] = {1, -1, 0, 0}, dy[] = {0, 0, 1, -1}; int n, m; int a[55][55]; int vis[55][55]; vector<pair<int, int> > g[3]; bool check(int x, int y) { return x > 0 && x <= n && y > 0 && y <= m; } void dfs1(int x, int y, int c) { vis[x][y] = c + 1; g[c].push_back(make_pair(x, y)); for (int i = 0; i < 4; i++) { int nx = x + dx[i], ny = y + dy[i]; if (check(nx, ny) && a[nx][ny] && !vis[nx][ny]) { dfs1(nx, ny, c); } } } int getj(int xx, int yx, int xy, int yy) { return abs(xx - xy) + abs(yx - yy); } int sb[55][55][3]; int main() { //freopen("mst1.in", "r", stdin); // freopen("mst.out", "w", stdout); scanf("%d%d", &n, &m); for (int i = 1; i<= n; i++) { for (int j = 1; j <= m; j++) { char c; scanf(" %c", &c); if (c == 'X') a[i][j] = 1; else a[i][j] = 0; } } int cnt = 0; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (a[i][j] && !vis[i][j]) { dfs1(i, j, cnt++); } } } memset(sb, 0x3f, sizeof(sb)); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { for (int c = 0; c < 3; c++) { for (int k = 0; k < g[c].size(); k++) { sb[i][j][c] = min(sb[i][j][c], getj(i, j, g[c][k].first, g[c][k].second)); } } } } // for (int c = 0; c < 3; c++) { // for (int i = 1; i <= n; i++) { // for (int j = 1; j <= m; j++) { // printf("%3d ", sb[i][j][c]); // } // printf("\n"); // } // printf("\n"); // } int ans = 0x3f3f3f3f; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { ans = min(ans, sb[i][j][0] + sb[i][j][1] + sb[i][j][2] - 2); } } for (int c = 0; c < 3; c++) { int a1 = 0x3f3f3f3f, a2 = 0x3f3f3f3f; if (c == 0) { for (int k = 0; k < g[c].size(); k++) { a1 = min(a1, sb[g[c][k].first][g[c][k].second][1]); } for (int k = 0; k < g[c].size(); k++) { a2 = min(a2, sb[g[c][k].first][g[c][k].second][2]); } } else if (c == 1) { for (int k = 0; k < g[c].size(); k++) { a1 = min(a1, sb[g[c][k].first][g[c][k].second][0]); } for (int k = 0; k < g[c].size(); k++) { a2 = min(a2, sb[g[c][k].first][g[c][k].second][2]); } } else if (c == 2) { for (int k = 0; k < g[c].size(); k++) { a1 = min(a1, sb[g[c][k].first][g[c][k].second][0]); } for (int k = 0; k < g[c].size(); k++) { a2 = min(a2, sb[g[c][k].first][g[c][k].second][1]); } } ans = min(ans, a1 + a2 - 2); } printf("%d\n", ans); return 0; }