from collections import deque from collections.abc import Iterator def neighbors4(r: int, c: int) -> Iterator[tuple[int, int]]: for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]: nr = r + dr nc = c + dc if not (0 <= nr < H and 0 <= nc < W): continue yield nr, nc def fill(row, col, g, val): q = deque([(row, col)]) while q: r, c = q.popleft() if g[r][c] == val: continue g[r][c] = val for nr, nc in neighbors4(r, c): if g[nr][nc] == val: continue if G[nr][nc] == '#': continue q.append((nr, nc)) INF = 1 << 60 W, H = map(int, input().split()) G = [input() for _ in range(H)] g = [[-1] * W for _ in range(H)] marker = 0 for i in range(H): for j in range(W): if g[i][j] != -1: continue if G[i][j] == '#': continue fill(i, j, g, marker) marker += 1 ans = INF for r1 in range(H): for c1 in range(W): if g[r1][c1] != 0: continue for r2 in range(H): for c2 in range(W): if g[r2][c2] != 1: continue d = abs(r1 - r2) + abs(c1 - c2) ans = min(ans, d - 1) print(ans)