inputs = STDIN.readlines.map(&:chomp) N = inputs[0].to_i class Koma def initialize(pos) @pos = pos end attr_reader :pos def ==(other) @pos == other.pos end def valid? 1 <= @pos && @pos <= N end def goal? @pos == N end def next_cands ons = @pos.to_s(2).count('1') [Koma.new(@pos + ons), Koma.new(@pos - ons)].select(&:valid?) end end def search queue = [[Koma.new(1)]] visited = { 1 => true } until queue.empty? path = queue.shift cands = path.last.next_cands.reject { |cand| visited[cand.pos] } return path.size + 1 if cands.any?(&:goal?) queue.push(*cands.map { |cand| path + [cand] }) visited.update(cands.map { |cand| [cand.pos, true] }.to_h) end -1 end puts N == 1 ? 1 : search