def pp(c) c.each do |l| puts l end end $dx = [0,1,0,-1] $dy = [1,0,-1,0] def bfs(f, sy, sx, h, w) steps = Array.new(h).map{Array.new(w,-1)} q = [[sy,sx]] visited = [[sy,sx]] while q.size > 0 sy, sx = q.shift for i in 0..3 cy = sy + $dy[i] cx = sx + $dx[i] if cy.between?(0,h-1) && cx.between?(0,w-1) && steps[cy][cx]== -1 && f[cy][cx]!="#" q.push([cy,cx]) visited.push([cy,cx]) steps[cy][cx] = steps[sy][sx] + 1 end end end return steps end $m = 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]) 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,"0",h,w) bl = true break end break if bl end #pp c bl = false ret = Float::INFINITY while $m.size > 0 sy, sx = $m.shift for i in 0..3 cy = sy + $dy[i] cx = sx + $dx[i] if c[cy][cx] == "." ret = c[sy][sx].to_i if c[sy][sx].to_i < ret elsif cy.between?(1,h-2) && cx.between?(1,w-2) && c[cy][cx]=="\#" $m.push([cy,cx]) c[cy][cx] = (c[sy][sx].to_i + 1).to_s end end break if bl end p ret