def pp(c) c.each do |l| puts l end puts end $dx = [0,1,0,-1] $dy = [1,0,-1,0] $m = Array.new $mm = Array.new def fill(c,i,j,ch,h,w) q = [[i,j]] while q.size > 0 sy, sx = q.shift c[sy][sx] = ch $m.push([sy,sx]) if ch == "a" $mm.push([sy,sx]) if ch == "b" for i in 0..3 cy = sy + $dy[i] cx = sx + $dx[i] if cy.between?(0,h-1) && cx.between?(0,w-1) && c[cy][cx]=="." q.push([cy,cx]) end end end end w, h = gets.split.map(&:to_i) c = h.times.map{gets.chomp} bl = false c.each_with_index do |line,i| line.each_char.with_index do |cc,j| next unless cc == "." fill(c,i,j,"a",h,w) bl = true break end break if bl end bl = false c.each_with_index do |line,i| line.each_char.with_index do |cc,j| next unless cc == "." fill(c,i,j,"b",h,w) bl = true break end break if bl end #pp c ret = Float::INFINITY $m.each do |p| $mm.each do |pp| t = (p[0] - pp[0]).abs + (p[1] - pp[1]).abs - 1 ret = t if t < ret end end p ret