#include using namespace std; typedef long long ll; #define rep(i, n) for(ll i = 0, i##_len = (n); i < i##_len; i++) #define reps(i, s, n) for(ll i = (s), i##_len = (n); i < i##_len; i++) #define rrep(i, n) for(ll i = (n) - 1; i >= 0; i--) #define rreps(i, e, n) for(ll i = (n) - 1; i >= (e); i--) #define all(x) (x).begin(), (x).end() #define rall(x) (x).rbegin(), (x).rend() #define sz(x) ((ll)(x).size()) #define len(x) ((ll)(x).length()) #define endl "\n" struct UnionFind { UnionFind() {} UnionFind(int n) { resize(n); } void resize(int n) { par.resize(n, -1); } int root(int x) { if (par[x] < 0) return x; return par[x] = root(par[x]); } bool merge(int x, int y) { int rx = root(x); int ry = root(y); if (rx == ry) return false; if (par[rx] > par[ry]) swap(rx, ry); par[rx] += par[ry]; par[ry] = rx; return true; } bool is_same(int x, int y) { return (root(x) == root(y)); } int size(int x) { return -par[root(x)]; } private: vector par; }; struct S { ll y, x, d, g; }; int main() { cin.tie(0); ios::sync_with_stdio(false); // ifstream in("input.txt"); // cin.rdbuf(in.rdbuf()); const ll inf = LONG_LONG_MAX / 2 - 1; const ll d[4][2] = {{0, -1}, {0, 1}, {1, 0}, {-1, 0}}; ll w, h; cin >> w >> h; vector c(h); rep(i, h) cin >> c[i]; UnionFind uf(w * h); rep(y, h) { rep(x, w) { if (c[y][x] != '.') continue; ll idx = y * w + x; rep(i, 4) { ll ny = y + d[i][0]; ll nx = x + d[i][1]; ll ni = ny * w + nx; if ((ny < 0) || (ny >= h) || (nx < 0) || (nx >= w)) continue; if (c[ny][nx] != '.') continue; uf.merge(idx, ni); } } } set s; rep(y, h) { rep(x, w) { if (c[y][x] != '.') continue; s.insert(uf.root(y * w + x)); } } vector grp; for(auto &x : s) grp.push_back(x); queue q; vector>> dist(h, vector>(w, vector(2, inf))); rep(y, h) { rep(x, w) { if (c[y][x] == '.') { rep(i, 4) { ll ny = y + d[i][0]; ll nx = x + d[i][1]; if ((ny < 0) || (ny >= h) || (nx < 0) || (nx >= w)) continue; if (c[ny][nx] != '#') continue; ll rt = uf.root(y * w + x), ng; rep(j, sz(grp)) { if (grp[j] == rt) { ng = j; } } q.push((S){ny, nx, 1, ng}); dist[ny][nx][ng] = 1; } } } } while(!q.empty()) { S cur = q.front(); q.pop(); if (dist[cur.y][cur.x][cur.g] != cur.d) continue; rep(i, 4) { ll ny = cur.y + d[i][0]; ll nx = cur.x + d[i][1]; ll nd = cur.d + 1; if ((ny < 0) || (ny >= h) || (nx < 0) || (nx >= w)) continue; if (c[ny][nx] == '.') { if (cur.g != uf.root(ny * w + nx)) { dist[ny][nx][cur.g] = min(dist[ny][nx][cur.g], nd); } } else { if (dist[ny][nx][cur.g] > nd) { dist[ny][nx][cur.g] = nd; q.push((S){ny, nx, nd, cur.g}); } } } } ll ans = inf; rep(y, h) { rep(x, w) { if (c[y][x] != '.') continue; ll g = uf.root(y * w + x); ll t = 1; rep(i, sz(grp)) { if (grp[i] == g) { t -= i; break; } } ans = min(ans, dist[y][x][t]); } } cout << (ans - 1) << endl; return 0; }