class Queens
  def initialize(nqueens = 8)
   @col = []
   @qpos = []
   @up = []
   @down = []
   @nqueens = nqueens
   (0...@nqueens).each { |i|
    @col[i] = @qpos[i] = 0
   
   (-@nqueens...@nqueens).each { |i|
    @up[i+@nqueens] = 0
    @down[i+@nqueens] = 0
   
  end
  def out(block)
   if block then
    block.call(@qpos)
   else
    puts((0...@nqueens).collect { |i| @qpos[i].to_s }.join(" "))
   end
  end
  
  def expand(n,block)
   (0...@nqueens).each { |c|
    if @col[c] == 0 && @up[n+c] == 0 &&
      @down[n-c+@nqueens] == 0 then
     @qpos[n] = c
     if n+1 >= @nqueens then
      out(block)
     else
      @col[c] = @up[n+c] = @down[n-c+@nqueens] = 1
      expand(n+1,block)
      @col[c] = @up[n+c] = @down[n-c+@nqueens] = 0
     end
    end
   
  end
  
  def run(&block)
   while true do
    expand(0,block)
   end
  end
 end
 if __FILE__ == $0 then
  Queens.new.run
 end