def bfs(sy: int, sx: int, num: int) -> None: dist[sy][sx] = num q = deque() q.append((sy, sx)) while q: vy, vx = q.popleft() for dy, dx in ((1, 0), (-1, 0), (0, 1), (0, -1)): y = vy + dy x = vx + dx if not (0 <= x < w and 0 <= y < h): continue if grid[y][x] == "#": continue if dist[y][x] != -1: continue dist[y][x] = dist[vy][vx] q.append((y, x)) w, h = map(int, input().split()) grid = [list(input()) for _ in range(h)] from collections import deque dist = [[-1] * w for _ in range(h)] cnt = 1 for i in range(h): for j in range(w): if grid[i][j] == "." and dist[i][j] == -1: bfs(i, j, 1000 * cnt) cnt += 1 a = [] b = [] for i in range(h): for j in range(w): if dist[i][j] == 1000: a.append((i, j)) if dist[i][j] == 2000: b.append((i, j)) ans = 10 ** 18 for xi, yi in a: for xj, yj in b: ans = min(ans, abs(xi - xj) + abs(yi - yj)) print(ans - 1)