def f(x,y,w,h,no) dx=[1,0,-1,0] dy=[0,1,0,-1] $map[y][x]=no.to_s $hs[no]<<[y,x] 4.times{|i| x1=x+dx[i] y1=y+dy[i] if x1<0 || x1>=w || y1<0 || y1>=h || $map[y1][x1]!="." next end f(x1,y1,w,h,no) } end w,h=gets.split.map{|e| e.to_i} $map=STDIN.read.split $hs=[[],[]] no=0 h.times{|y| w.times{|x| if $map[y][x]=="." f(x,y,w,h,no) no+=1 end } } ans=10000 $hs[0].each{|e1| $hs[1].each{|e2| d=(e1[0]-e2[0]).abs+(e1[1]-e2[1]).abs-1 ans=[ans,d].min } } puts ans