from collections import deque W, H = map(int, input().split()) C = [list(input()) for _ in range(H)] routes = [] for h in range(H-1): for w in range(W-1): if C[h][w] == '.': r = [] q = deque() q.append((h, w)) C[h][w] = '*' #done r.append((h, w)) while q: y0, x0 = q.popleft() C[y0][x0] = '*' #done r.append((y0, x0)) for dy, dx in ((-1, 0), (0, 1), (1, 0), (0, -1)): y1, x1 = y0 + dy, x0 + dx if 0 <= y1 < H and 0 <= x1 < W and C[y1][x1] == '.': q.append((y1, x1)) C[y1][x1] = '*' #done r.append((y1, x1)) routes.append(r) ans = H * W for p0 in routes[0]: for p1 in routes[1]: d = abs(p0[0] - p1[0]) + abs(p0[1] - p1[1]) if d - 1 < ans: ans = d - 1 print(ans)