0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

オフラインリアルタイムどう書く第四回の参考問題 解答(Ruby)

Last updated at Posted at 2012-09-17

オフラインリアルタイムどう書く第四回の参考問題のrubyでの解答です。
問題はこちら http://qiita.com/items/9c514267214d3917edf2

class Route
  def initialize(sz)
    @sz = sz
    @nodes = []
    (sz * sz).times do |i|
      node = []
      node << (i - 1) unless (i % sz) == 0
      node << (i + 1) unless (i % sz) == (sz - 1)
      node << (i - sz) if i > sz
      node << (i + sz) if i < (sz * (sz - 1)) 
      @nodes << node
    end
  end

  def solve(xs)
    xs.split(' ').each do |x|
      i1, i2 = x.split('').map{|e| ('a'..'y').to_a.index(e)}
      @nodes[i1].delete(i2)
      @nodes[i2].delete(i1)
    end

    @done = {}
    @count = 0
    move(0)
    @count
  end

  def move(i)
    return if @done[i]
    if i == @sz * @sz - 1
      @count += 1
      return
    end
    @done[i] = true
    @nodes[i].each do |j|
      move(j)
    end
    @done[i] = false
  end
end

DATA.readlines.each do |line|
  puts Route.new(5).solve(line.split(' -> ').first.gsub('"',''))
end

__END__
"" -> 8512 #そのまま。これが最大値。
"af" -> 4256 #対称性より半分になる
"xy" -> 4256 #対称性より半分になる
"pq qr rs st di in ns sx" -> 184 #3x3マスと同値
"af pq qr rs st di in ns sx" -> 92 #3x3マスのパターンの半分
"bg ch di ij no st" -> 185 #3x3マスのパターン +1
"bc af ch di no kp mr ns ot pu rs" -> 16 #4x2x2
"ab af" -> 0 #入口を塞いだ
"ty xy" -> 0 #出口を塞いだ
"bg ch ej gh lm lq mr ot rs sx" -> 11 #2x4+3
"ty ch hi mn kp mr rs sx" -> 18 #6*3
"xy ch hi mn kp mr rs sx" -> 32 #4*8
"ch hi mn kp mr rs sx" -> 50 #6*3+4*8
"ab cd uv wx" -> 621 
"gh mn st lq qr" -> 685 
"fg gl lm mr rs" -> 171
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?