module NQueen def expand(size, &block) size.times do |row| nqueen(size, [], row, &block) end end def nqueen(size, board, row, &block) board.each_with_index do |v, c| check = v - row return if check == 0 || check.abs == board.length - c end board = board + [row] if board.length == size yield(board) return end size.times do |r| nqueen(size, board, r, &block) end end module_function :expand, :nqueen end if __FILE__ == $0 size = (ARGV.shift || '5').to_i nq = NQueen.expand(size) do |x| puts x.join(" ") end end