#include #define rep(i, n) for (int i = 0; i < n; ++i) using ll = long long; using namespace std; const int INF = 1e9; int main() { int H, W; cin >> W >> H; vector S(H); rep(i, H) cin >> S[i]; vector>> hole(2); auto bfs = [&](int cn, int y, int x) { queue> que; que.push({y, x}); S[y][x] = '#'; hole[cn].push_back({y, x}); int dx[] = {-1, 1, 0, 0}, dy[] = {0, 0, -1, 1}; while (!que.empty()) { pair now = que.front(); que.pop(); rep(i, 4) { int ny = now.first + dy[i]; int nx = now.second + dx[i]; if (ny >= 0 && ny < H && nx >= 0 && nx < W && S[ny][nx] == '.') { hole[cn].push_back({ny, nx}); S[ny][nx] = '#'; que.push({ny, nx}); } } } }; int cnt = 0; rep(i, H) rep(j, W) { if (S[i][j] == '.') { bfs(cnt, i, j); ++cnt; } } int ans = INF; for (auto u : hole[0]) { for (auto v : hole[1]) { ans = min(ans, abs(u.first - v.first) + abs(u.second - v.second) - 1); } } cout << ans << endl; return 0; }