w,h=map(int,input().split()) l=[list(input()) for i in range(h)] n=h*w connection=[[] for i in range(h*w)] connection2=[[] for i in range(h*w)] for i in range(h): for j in range(w): if l[i][j]=='.': if i!=0: connection2[i*w+j].append((i-1)*w+j) if l[i-1][j]=='.': connection[i*w+j].append((i-1)*w+j) if i!=h-1: connection2[i*w+j].append((i+1)*w+j) if l[i+1][j]=='.': connection[i*w+j].append((i+1)*w+j) if j!=0: connection2[i*w+j].append(i*w+j-1) if l[i][j-1]=='.': connection[i*w+j].append(i*w+j-1) if j!=w-1: connection2[i*w+j].append(i*w+j+1) if l[i][j+1]=='.': connection[i*w+j].append(i*w+j+1) else: if i!=0: connection2[i*w+j].append((i-1)*w+j) if i!=h-1: connection2[i*w+j].append((i+1)*w+j) if j!=0: connection2[i*w+j].append(i*w+j-1) if j!=w-1: connection2[i*w+j].append(i*w+j+1) def bfs(v): distance=[-1]*n distance[v]=0 next=connection[v] next2=set() visited=[-1]*n visited[v]=1 visitct=1 ct=0 while len(next)!=0 and visitct!=n: ct+=1 for i in range(len(next)): if visited[next[i]]==-1: distance[next[i]]=ct visited[next[i]]=1 visitct+=1 for j in range(len(connection[next[i]])): if visited[connection[next[i]][j]]==-1: next2.add(connection[next[i]][j]) next=list(next2) next2=set() return distance def bfs2(l): distance=[-1]*n next=set() next2=set() visited=[-1]*n visitct=0 for i in range(len(l)): distance[l[i]]=0 for j in range(len(connection2[l[i]])): next.add(connection2[l[i]][j]) visited[l[i]]=1 visitct=+1 next=list(next) ct=0 while len(next)!=0 and visitct!=n: ct+=1 for i in range(len(next)): if visited[next[i]]==-1: distance[next[i]]=ct visited[next[i]]=1 visitct+=1 for j in range(len(connection2[next[i]])): if visited[connection2[next[i]][j]]==-1: next2.add(connection2[next[i]][j]) next=list(next2) next2=set() return distance for i in range(n): if len(connection[i])!=0: x=i break L=bfs(x) L2=[] for i in range(n): if L[i]!=-1: L2.append(i) ans=[] L3=bfs2(L2) for i in range(n): if L[i]==-1 and l[i//w][i%w]=='.': ans.append(L3[i]-1) print(min(ans))