#include #include #include #include #include #include using namespace std; typedef long long int ll; typedef pair pii; typedef tuple tiii; typedef vector vi; #define REP(i,x) for(int i=0;i<(int)(x);i++) #define ALL(container) (container).begin(), (container).end() pii shifts[] = {{1,0},{0,1},{-1,0},{0,-1}}; int f[200][200]; int visit[200][200]; vector vs[3]; int main(int argc, char *argv[]){ ios::sync_with_stdio(false); int w,h; cin >> w >> h; REP(i, 200) REP(j, 200) f[i][j] = -2; REP(i, h) { string s; cin >> s; REP(j, w) { if(s[j] == '.') { f[i + 1][j + 1] = -1; } else { f[i + 1][j + 1] = 0; } } } int id = 1; REP(i, h+2) REP(j, w+2) { int sh = i + 1; int sw = j + 1; if(f[sh][sw] != -1) { continue; } queue q; q.push(make_tuple(sw,sh, id)); f[sh][sw] = id; vs[id].emplace_back(sw,sh); while(!q.empty()) { const auto t = q.front(); q.pop(); for(int s = 0;s < 4;s++) { auto x = get<0>(t) + shifts[s].first; auto y = get<1>(t) + shifts[s].second; if(f[y][x] != -1) { continue; } f[y][x] = id; vs[id].emplace_back(x,y); q.push(make_tuple(x,y,id)); } } id++; } { REP(i, 200) REP(j, 200) visit[i][j] = 0; queue q; for(int i = 0;i < vs[1].size();i++) { auto t = vs[1][i]; for(int s = 0;s < 4;s++) { auto x = get<0>(t) + shifts[s].first; auto y = get<1>(t) + shifts[s].second; if(f[y][x] == 0) { if(!visit[y][x]) { q.push(make_tuple(x,y,1)); visit[y][x] = true; } } } } //REP(i, h+2) //{ // REP(j, w+2) cout << f[i][j]; // cout << endl; //} while(!q.empty()) { const auto t = q.front(); q.pop(); auto c = get<2>(t); for(int s = 0;s < 4;s++) { auto x = get<0>(t) + shifts[s].first; auto y = get<1>(t) + shifts[s].second; if(f[y][x] == 0) { if(!visit[y][x]) { q.push(make_tuple(x,y,c+1)); visit[y][x] = true; } } if(f[y][x] == 2) { cout << c << endl; return 0; } } } } return 0; }