import core.thread; import std.conv, std.stdio, std.string; import std.algorithm, std.array, std.bigint, std.container, std.math, std.range, std.regex; // Input class EOFException : Throwable { this() { super("EOF"); } } string[] tokens; string readToken() { for (; tokens.empty; ) { tokens = readln.split; if (tokens.empty && stdin.eof) throw new EOFException; } auto token = tokens[0]; tokens.popFront; return token; } int readInt() { return to!int(readToken); } long readLong() { return to!long(readToken); } real readReal() { return to!real(readToken); } // chmin/chmax void chmin(T)(ref T t, in T f) { if (t > f) t = f; } void chmax(T)(ref T t, in T f) { if (t < f) t = f; } // Pair struct Pair(S, T) { S x; T y; int opCmp( const Pair p) const { return (x < p.x) ? -1 : (x > p.x) ? +1 : (y < p.y) ? -1 : (y > p.y) ? +1 : 0; } int opCmp(ref const Pair p) const { return (x < p.x) ? -1 : (x > p.x) ? +1 : (y < p.y) ? -1 : (y > p.y) ? +1 : 0; } string toString() const { return "(" ~ to!string(x) ~ ", " ~ to!string(y) ~ ")"; } } auto pair(S, T)(inout(S) x, inout(T) y) { return Pair!(S, T)(x, y); } // Array int binarySearch(T)(in T[] as, in bool delegate(T) test) { int low = -1, upp = as.length; for (; low + 1 < upp; ) { int mid = (low + upp) >> 1; (test(as[mid]) ? low : upp) = mid; } return upp; } int lowerBound(T)(in T[] as, in T val) { return as.binarySearch((T a) { return (a < val); }); } int upperBound(T)(in T[] as, in T val) { return as.binarySearch((T a) { return (a <= val); }); } T[] unique(T)(in T[] as) { T[] bs; foreach (a; as) if (bs.empty || bs[$ - 1] != a) bs ~= a; return bs; } int M, N; char[][] A; void main(string[] args) { try { for (; ; ) { N = readInt; M = readInt; A = new char[][M]; foreach (x; 0 .. M) { A[x] = readToken.to!(char[]); } void dfs(int x, int y) { A[x][y] = '!'; foreach (dx; -1 .. +1 + 1) foreach (dy; -1 .. +1 + 1) if (dx^^2 + dy^^2 == 1) { const xx = x + dx; const yy = y + dy; if (0 <= xx && xx < M && 0 <= yy && yy < N && A[xx][yy] == '.') { dfs(xx, yy); } } } foreach (x; 0 .. M) foreach (y; 0 .. N) { if (A[x][y] == '.') { dfs(x, y); goto done; } } done:; debug{ foreach(x;0..M)writeln(A[x]); } int ans = M + N; foreach (x0; 0 .. M) foreach (y0; 0 .. N) if (A[x0][y0] == '!') foreach (x1; 0 .. M) foreach (y1; 0 .. N) if (A[x1][y1] == '.') { chmin(ans, abs(x0 - x1) + abs(y0 - y1)); } writeln(ans - 1); } } catch (EOFException) {} }