結果

問題 No.157 2つの空洞
ユーザー simansiman
提出日時 2015-04-03 07:39:45
言語 Ruby
(3.3.0)
結果
TLE  
実行時間 -
コード長 1,517 bytes
コンパイル時間 53 ms
コンパイル使用メモリ 11,468 KB
実行使用メモリ 15,476 KB
最終ジャッジ日時 2023-09-17 03:57:17
合計ジャッジ時間 5,545 ms
ジャッジサーバーID
(参考情報)
judge11 / judge15
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 67 ms
15,372 KB
testcase_01 AC 67 ms
15,060 KB
testcase_02 AC 70 ms
15,136 KB
testcase_03 AC 73 ms
15,224 KB
testcase_04 AC 69 ms
15,048 KB
testcase_05 AC 68 ms
15,152 KB
testcase_06 AC 69 ms
15,124 KB
testcase_07 AC 74 ms
15,268 KB
testcase_08 AC 69 ms
15,324 KB
testcase_09 AC 73 ms
15,232 KB
testcase_10 AC 69 ms
15,136 KB
testcase_11 AC 72 ms
15,256 KB
testcase_12 AC 71 ms
15,252 KB
testcase_13 AC 69 ms
15,312 KB
testcase_14 AC 103 ms
15,232 KB
testcase_15 AC 84 ms
15,268 KB
testcase_16 AC 86 ms
15,476 KB
testcase_17 TLE -
testcase_18 -- -
testcase_19 -- -
権限があれば一括ダウンロードができます
コンパイルメッセージ
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]]

    while coords.any?
      y, x = coords.shift

      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