結果

問題 No.157 2つの空洞
ユーザー simansiman
提出日時 2015-04-03 07:42:58
言語 Ruby
(3.3.0)
結果
AC  
実行時間 110 ms / 2,000 ms
コード長 1,630 bytes
コンパイル時間 42 ms
コンパイル使用メモリ 11,308 KB
実行使用メモリ 15,504 KB
最終ジャッジ日時 2023-09-17 03:57:24
合計ジャッジ時間 2,737 ms
ジャッジサーバーID
(参考情報)
judge12 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 83 ms
15,252 KB
testcase_01 AC 82 ms
15,180 KB
testcase_02 AC 83 ms
15,164 KB
testcase_03 AC 83 ms
15,152 KB
testcase_04 AC 84 ms
15,100 KB
testcase_05 AC 84 ms
15,344 KB
testcase_06 AC 85 ms
15,308 KB
testcase_07 AC 84 ms
15,272 KB
testcase_08 AC 82 ms
15,312 KB
testcase_09 AC 84 ms
15,308 KB
testcase_10 AC 85 ms
15,040 KB
testcase_11 AC 88 ms
15,308 KB
testcase_12 AC 85 ms
15,168 KB
testcase_13 AC 86 ms
15,156 KB
testcase_14 AC 110 ms
15,504 KB
testcase_15 AC 99 ms
15,184 KB
testcase_16 AC 101 ms
15,192 KB
testcase_17 AC 96 ms
15,196 KB
testcase_18 AC 92 ms
15,192 KB
testcase_19 AC 84 ms
15,140 KB
権限があれば一括ダウンロードができます
コンパイルメッセージ
Syntax OK

ソースコード

diff #

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
0