#include using namespace std; using ll =long long; #define rep(i,N) for(int (i)=0;(i)<(N);++(i)) #define SORT(i) sort((i).begin(),(i).end()) constexpr ll INF = 2000000000; constexpr ll mod = 1000000007; int y[4] = { 0,1,0,-1 }; int x[4] = { 1,0,-1,0 }; int main() { int W, H; cin >> W >> H; vector>maze(H, vector(W)); vector>dist(H, vector(W, -1)); queue>que; queue>q; bool is = true; rep(i, H) { rep(j, W) { cin >> maze[i][j]; if (is) { if (maze[i][j] == '.') { dist[i][j] = INF; que.push(make_pair(i, j)); q.push(make_pair(i, j)); is = false; } } } } int ny, nx; while (!que.empty()) { pairN = que.front(); que.pop(); rep(i, 4) { ny = N.first + y[i], nx = N.second + x[i]; if (ny < 0 || nx < 0 || ny >= H || nx >= W || dist[ny][nx] != -1 || maze[ny][nx] == '#')continue; dist[ny][nx] = INF; que.push(make_pair(ny, nx)); q.push(make_pair(ny, nx)); } } int ans = INF; while (!q.empty()) { pairN = q.front();q.pop(); rep(i, 4) { ny = N.first + y[i], nx = N.second + x[i]; if (ny < 0 || nx < 0 || ny >= H || nx >= W || dist[ny][nx] != -1)continue; if (dist[N.first][N.second] == INF) { dist[ny][nx] = 1; } else if (maze[ny][nx] == '.') { ans = min(ans, dist[N.first][N.second]); dist[ny][nx] = dist[N.first][N.second] + 1; } else { dist[ny][nx] = dist[N.first][N.second] + 1; } q.push(make_pair(ny, nx)); } } cout << ans << "\n"; return 0; }