IPSJの課題に合うように書き直してみる。課題の都合により次の行に進めるかどうかを試すメソッドをわけた。
class NQueen def concat(board, row) board.each_with_index do |v, col| return nil if v == row return nil if (v - row).abs == board.size - col end board + [row] end def nq(size, board=[]) found = 0 size.times do |row| fwd = concat(board, row) next unless fwd return 1 if fwd.size == size found += nq(size, fwd) end found end end if __FILE__ == $0 size = (ARGV.shift || '5').to_i puts NQueen.new.nq(size) end