import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines import numpy as np W,H = map(int,readline().split()) grid = np.frombuffer(read(),'S1').reshape(H,-1)[:,:W].astype('U1') grid = np.ravel(grid).tolist() component = [0] * (H*W) n = 1 for i,x in enumerate(grid): if x != '.': continue if component[i]: continue stack = [i] component[i] = n while stack: x = stack.pop() for dx in [1,-1,W,-W]: y = x+dx if grid[y] != '.': continue if component[y]: continue component[y] = n stack.append(y) n += 1 component = np.array(component).reshape((H,W)) component dist = np.where(component == 1, 0, 100) for _ in range(4): dist = dist.T[::-1] n = dist.shape[0] for i in range(1,n): dist[i] = np.minimum(dist[i-1]+1, dist[i]) answer = dist[component == 2].min() - 1 print(answer)