#include using namespace std; using ll = long long; using PAIR = pair; using PAIRLL = pair; using vi = vector; using vll = vector; using vvi = vector; using vs = vector; #define rep(i,n) for(int i=0;i<(n);i++) #define INF 100000000 #define REP(i,n) for(ll i=0;i=0;i--) #define FOR(i,a,b) for(ll i=a;i<=ll(b);i++) #define FORD(i,a,b) for(ll i=a;i>=ll(b);i--) #define FORA(i,I) for(const auto& i:I) //x:コンテナ #define ALL(x) x.begin(),x.end() #define SIZE(x) ll(x.size()) //定数 #define INF32 2147483647 //2.147483647×10^{9}:32bit整数のinf #define INF64 9223372036854775807 //9.223372036854775807×10^{18}:64bit整数のinf #define MOD 1000000007 //問題による #define F first #define S second //出力(空白区切りで昇順に) #define coutALL(x) for(auto i=x.begin();i!=--x.end();i++)cout<<*i<<" ";cout<<*--x.end()<> W >> H; vector lsHW(H); rep(i,H) cin >> lsHW[i]; deque> d; deque> d1; vector> ls1; vector> used(H,vector(W,false)); vector> used1(H,vector(W,false)); vector> lscost(H,vector(W,INF32)); vector dx = {1,-1,0,0}; vector dy = {0,0,1,-1}; int x,y; pair c; bool f = false; rep(i,H){ rep(j,W){ if (lsHW[i][j] == '.'){ d.push_back({i,j}); d1.push_back({i,j}); lscost[i][j] = 0; f = true; break; } } if (f){ break; } } while (d1.empty() == false){ c = d1.front(); d1.pop_front(); d.push_back(c); ls1.push_back(c); x = c.first; y = c.second; if (used1[x][y]){ continue; } used1[x][y] = true; rep(i,4){ int nextx = x+dx[i]; int nexty = y+dy[i]; if (0<=nextx && nextx lscost[x][y]){ lscost[nextx][nexty] = lscost[x][y]; d1.push_front({nextx,nexty}); } } } } } while (d.empty() == false){ c = d.front(); d.pop_front(); x = c.first; y = c.second; if (used[x][y]){ continue; } used[x][y] = true; rep(i,4){ int nextx = x+dx[i]; int nexty = y+dy[i]; if (0<=nextx && nextx lscost[x][y]+1){ lscost[nextx][nexty] = lscost[x][y]+1; d.push_back({nextx,nexty}); } } if (lsHW[nextx][nexty] == '.'){ if (lscost[nextx][nexty] > lscost[x][y]){ lscost[nextx][nexty] = lscost[x][y]; d.push_front({nextx,nexty}); } } } } } for (const auto & p:ls1){ x = p.first; y = p.second; lsHW[x][y] = '#'; } rep(i,H){ rep(j,W){ if (lsHW[i][j] == '.'){ cout << lscost[i][j] << endl; return 0; } } } }