#include #include #include #include using namespace std; #define RREP(i,s,e) for (int i = e-1; i >= s; i--) #define rrep(i,n) RREP(i,0,n) #define REP(i,s,e) for (int i = s; i < e; i++) #define rep(i,n) REP(i,0,n) #define INF 1e8 int main() { int w, h; cin >> w >> h; vector m; int square[h][w]; m.resize(h); rep (i,h) { cin >> m[i]; fill(square[i],square[i]+w,INF); } queue> next; bool found = false; rep (i,h) rep (j,w) { if (!found && m[i][j] == '.') { found = true; queue> q; q.push(make_pair(i,j)); next.push(make_tuple(i,j,0)); while (!q.empty()) { int a, b; tie(a,b) = q.front(); q.pop(); if (m[a][b] == 'S') continue; int x[4] = {-1, 0, 1, 0}; rep (k,4) { int u = a+x[k]; int v = b+x[(k+1)%4]; if (m[u][v] == '.') { q.push(make_pair(u,v)); next.push(make_tuple(u,v,0)); } } m[a][b] = 'S'; } } } int ans; while (!next.empty()) { int i, j, dis; tie(i,j,dis) = next.front(); next.pop(); if (m[i][j] == '.') { ans = dis - 1; break; } else if (square[i][j] == INF) { square[i][j] = dis; int x[4] = {-1, 0, 1, 0}; rep (k,4) { int u = i+x[k]; int v = j+x[(k+1)%4]; if (0 <= u && u < h && 0 <= v && v < w && m[u][v] != 'S') next.push(make_tuple(u,v,dis+1)); } } } cout << ans << endl; return 0; }