#include using namespace std; #define rep(i, n) for(int i = 0; i < (int)n; ++i) #define FOR(i, a, b) for(int i = a; i < (int)b; ++i) #define rrep(i, n) for(int i = ((int)n - 1); i >= 0; --i) typedef long long ll; typedef long double ld; const int Inf = 1e9; const double EPS = 1e-9; const int MOD = 1e9 + 7; int dx[4] = {0, 0, 1, -1}; int dy[4] = {1, -1, 0, 0}; int w, h; vector s; vector > g; void bfs(int sx, int sy, int color) { g[sx][sy] = color; rep (i, 4) { int nx, ny; nx = sx + dx[i], ny = sy + dy[i]; if (nx < 0 || nx >= h || ny < 0 || ny >= w) continue; if (s[nx][ny] == '#') continue; if (g[nx][ny] != 0) continue; bfs(nx, ny, color); } } int bfs(int sx, int sy) { vector > dist(h, vector(w, Inf)); queue > q; q.push(make_pair(sx, sy)); dist[sx][sy] = 0; while (!q.empty()) { int x = q.front().first, y = q.front().second; q.pop(); rep (i, 4) { int nx, ny; nx = x + dx[i], ny = y + dy[i]; if (nx < 0 || nx >= h || ny < 0 || ny >= w) continue; if (dist[nx][ny] != Inf) continue; if (g[nx][ny] == 2) return dist[x][y]; dist[nx][ny] = dist[x][y] + 1; q.push(make_pair(nx, ny)); } } return Inf; } int main() { cin.tie(nullptr); ios::sync_with_stdio(0); cin >> w >> h; s = vector(h); g = vector >(h, vector(w, 0)); rep (i, h) cin >> s[i]; int color = 1; rep (i, h) { rep (j, w) { if (s[i][j] == '.' && g[i][j] == 0) { bfs(i, j, color); color++; } } } int res = Inf; rep (i, h) { rep (j, w) { if (g[i][j] == 1) res = min(res, bfs(i, j)); } } cout << res << endl; return 0; }