while(n,m=l=gets.split.map(&:to_i))[0]>c=0
a=(1..m).map{gets.tr ?\n,?.}<<?.*n*2
q=[l]
r=[]
(x,y=q.shift
[[x,y+1],[x,y-1],[x+1,y],[x-1,y]].map{|i,j|i%=n+1;j%=m+1
d=a[j][i]
k=".#".index d
k&&(a[j][i]=?a;[q,r][k-c%2]<<[i,j])
d==?&&&(q=r=[];break)})while q[0]||(q,r=r.uniq,[];c+=1;q)[0]
p c/2
end