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)]] until queue.empty? path = queue.shift cands = path.last.next_cands.reject { |cand| (queue + path).flatten.include?(cand) } return path.size + 1 if cands.any?(&:goal?) queue.push(*cands.map { |cand| path + [cand] }) end -1 end puts search