結果

問題 No.424 立体迷路
ユーザー simansiman
提出日時 2020-12-22 18:04:36
言語 Ruby
(3.3.0)
結果
AC  
実行時間 104 ms / 2,000 ms
コード長 1,549 bytes
コンパイル時間 460 ms
コンパイル使用メモリ 11,932 KB
実行使用メモリ 16,472 KB
最終ジャッジ日時 2023-10-21 13:00:31
合計ジャッジ時間 4,757 ms
ジャッジサーバーID
(参考情報)
judge9 / judge10
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 87 ms
16,340 KB
testcase_01 AC 88 ms
16,340 KB
testcase_02 AC 89 ms
16,340 KB
testcase_03 AC 88 ms
16,340 KB
testcase_04 AC 87 ms
16,340 KB
testcase_05 AC 87 ms
16,340 KB
testcase_06 AC 88 ms
16,340 KB
testcase_07 AC 88 ms
16,340 KB
testcase_08 AC 89 ms
16,340 KB
testcase_09 AC 88 ms
16,340 KB
testcase_10 AC 89 ms
16,340 KB
testcase_11 AC 88 ms
16,340 KB
testcase_12 AC 89 ms
16,340 KB
testcase_13 AC 88 ms
16,340 KB
testcase_14 AC 91 ms
16,340 KB
testcase_15 AC 91 ms
16,340 KB
testcase_16 AC 88 ms
16,340 KB
testcase_17 AC 101 ms
16,472 KB
testcase_18 AC 101 ms
16,472 KB
testcase_19 AC 102 ms
16,472 KB
testcase_20 AC 101 ms
16,472 KB
testcase_21 AC 89 ms
16,340 KB
testcase_22 AC 89 ms
16,340 KB
testcase_23 AC 90 ms
16,340 KB
testcase_24 AC 102 ms
16,472 KB
testcase_25 AC 104 ms
16,472 KB
権限があれば一括ダウンロードができます
コンパイルメッセージ
Main.rb:81: warning: assigned but unused variable - nnz
Syntax OK

ソースコード

diff #

class UnionFind
  def initialize(n)
    @size = Array.new(n, 1)
    @rank = Array.new(n, 0)
    @parent = []

    (0..n).each do |i|
      @parent[i] = i
    end
  end

  def find(x)
    if @parent[x] == x
      x
    else
      @parent[x] = find(@parent[x])
    end
  end

  def unite(x, y)
    x = find(x)
    y = find(y)
    return if x == y

    if @rank[x] < @rank[y]
      @parent[x] = y
      @size[y] += @size[x]
    else
      @parent[y] = x
      @size[x] += @size[y]

      @rank[x] += 1 if @rank[x] == @rank[y]
    end
  end

  def same?(x, y)
    find(x) == find(y)
  end

  def size(x)
    @size[find(x)]
  end
end

H, W = gets.split.map(&:to_i)
SY, SX, GY, GX = gets.split.map(&:to_i)
B = H.times.map { gets.chomp.chars.map(&:to_i) }
uf = UnionFind.new(10_000)

def calc_z(y, x)
  y * W + x
end

DY = [-1, 0, 1, 0, -2, 0, 2, 0]
DX = [0, 1, 0, -1, 0, 2, 0, -2]

H.times do |y|
  W.times do |x|
    h = B[y][x]
    z = calc_z(y, x)

    8.times do |i|
      ny = y + DY[i]
      nx = x + DX[i]
      nz = calc_z(ny, nx)
      next if ny < 0 || nx < 0 || H <= ny || W <= nx
      next if uf.same?(z, nz)

      nh = B[ny][nx]

      if i < 4
        d = (h - nh).abs
        next if d >= 2

        uf.unite(z, nz)
      else
        next if h != nh

        nny = y + DY[i - 4]
        nnx = x + DX[i - 4]
        nnz = calc_z(nny, nnx)
        nnh = B[nny][nnx]
        next if h <= nnh

        uf.unite(z, nz)
      end
    end
  end
end

if uf.same?(calc_z(SY - 1, SX - 1), calc_z(GY - 1, GX - 1))
  puts 'YES'
else
  puts 'NO'
end
0