def g;gets.split.map(&:to_i)end w,h=g c=(0...h).map{gets+?+}+[?+*w] fx=fy=0 fy=(0...h).find{|i|fx=(0...w).find{|j|c[i][j]==?.}} q=[[fx,fy,0]] c[fy][fx]=?+ n=0 while q[n] x,y=q[n] [[x+1,y],[x-1,y],[x,y+1],[x,y-1]].each{|tx,ty| if c[ty][tx]==?. q<<[tx,ty,0] c[ty][tx]=?+ end } n+=1 end while q[0] x,y,i=q.shift [[x+1,y],[x-1,y],[x,y+1],[x,y-1]].each{|tx,ty| case c[ty][tx] when ?. p i exit when ?# q<<[tx,ty,i+1] c[ty][tx]=?+ end } end