class Yukicoder attr_accessor :field, :width, :height DX = [1, 0, -1, 0] DY = [0, 1, 0, -1] def initialize @width, @height = gets.chomp.split(' ').map(&:to_i) @field = [] height.times do |y| @field << gets.chomp.split('') end id = 0 height.times do |y| width.times do |x| if field[y][x] == '.' bfs(y, x, id) id += 1 end end end min_dist = Float::INFINITY height.times do |y| width.times do |x| if field[y][x] == '0' min_dist = [min_dist, calc_dist(y, x)].min end end end puts min_dist end def calc_dist(y, x) coords = [[y,x,0]] check_list = Hash.new(false) while coords.any? y, x, dist = coords.shift return dist - 1 if field[y][x] == '1' next if check_list[y * width + x] check_list[y * width + x] = true 4.times do |i| ny = y + DY[i] nx = x + DX[i] if is_wall?(ny, nx) && field[ny][nx] != '0' coords << [ny, nx, dist + 1] end end end Float::INFINITY end def is_wall?(y, x) 0 <= y && y < height && 0 <= x && x < width end def bfs(y, x, id) coords = [[y,x]] check_list = Hash.new(false) while coords.any? y, x = coords.shift next if check_list[y * width + x] check_list[y * width + x] = true field[y][x] = id.to_s 4.times do |i| ny = y + DY[i] nx = x + DX[i] if is_wall?(ny, nx) && field[ny][nx] == '.' coords << [ny, nx] end end end end end Yukicoder.new