#include using namespace std; #define rep(i, n) for (int i = 0; i < (n); ++i) using ll = long long; using ull = unsigned long long; int main() { cin.tie(nullptr)->sync_with_stdio(false); int w, h; cin >> w >> h; vector Grid(h, vector(w)); rep(i, h) rep(j, w) cin >> Grid[i][j]; vector vis(h, vector(w, false)); constexpr array dx = { 1, 0, -1, 0 }; constexpr array dy = { 0, 1, 0, -1 }; const auto inRange = [&](int i, int j) { return 0 <= i && i < h && 0 <= j && j < w; }; { bool f = false; rep(i, h) { rep(j, w) { if (Grid[i][j] != '.') continue; queue> que; que.push({ i, j }); vis[i][j] = true; while (!que.empty()) { auto [x, y] = que.front(); que.pop(); rep(d, 4) { int nx = x + dx[d], ny = y + dy[d]; if (!inRange(nx, ny)) continue; if (!vis[nx][ny] && Grid[nx][ny] == '.') { vis[nx][ny] = true; que.push({ nx, ny }); } } } f = true; break; } if (f) break; } } vector dist(h, vector(w, 1e9)); queue> q; rep(i, h) rep(j, w) { if (vis[i][j]) dist[i][j] = 0, q.push({ i, j }); } while (!q.empty()) { auto [x, y] = q.front(); q.pop(); rep(d, 4) { int nx = x + dx[d], ny = y + dy[d]; if (!inRange(nx, ny)) continue; if (dist[nx][ny] > dist[x][y] + 1) { dist[nx][ny] = dist[x][y] + 1; q.push({ nx, ny }); } } } int ans = 1e9; rep(i, h) rep(j, w) if (Grid[i][j] == '.' && !vis[i][j]) ans = min(ans, dist[i][j]); cout << ans - 1 << '\n'; return 0; }