from itertools import product def main(): w, h = map(int, input().split()) g = [list(input()) for _ in range(h)] def dfs(x, y): g[x][y] = '#' yield [x, y] dx = [1, 0, -1, 0, 1, -1, -1, 1] dy = [0, 1, 0, -1, 1, 1, -1, -1] for dx, dy in zip(dx[:4], dy[:4]): nx = x + dx ny = y + dy if not (0 <= nx < h and 0 <= ny < w): continue if g[nx][ny] == '.': yield from dfs(nx, ny) cave1, cave2 = [], [] is_first = True for i, j in product(range(h), range(w)): if g[i][j] == '.': if is_first: cave1 = list(dfs(i, j)) is_first = False else: cave2 = list(dfs(i, j)) break ans = 1 << 60 for x1, y1 in cave1: for x2, y2 in cave2: ans = min(ans, abs(x1 - x2) + abs(y1 - y2) - 1) print(ans) if __name__ == "__main__": main()