八后问题Ruby02

Queen.rb

class Queen
  
  def initialize()
    @v=0
  end
  
  def canSetQueen(lst,s,x,y)
      lstNo = Array.new()
    
      for i in 0..s-1 do
        p = Pt.new(x,i)
        lstNo.push(p)
      end
      
      for j in 0..s-1 do
        p = Pt.new(j,y)
        lstNo.push(p)
      end 
      
      x0=x
      y0=y
      while x0<s and y0<s
        p=Pt.new(x0,y0)
        lstNo.push(p)
        x0=x0+1
        y0=y0+1
      end
      
      x0=x
      y0=y
      while x0>=0 and y0>=0
        p=Pt.new(x0,y0)
        lstNo.push(p)
        x0=x0-1
        y0=y0-1
      end
      
      x0=x
      y0=y
      while x0>=0 and y0<s
        p=Pt.new(x0,y0)
        lstNo.push(p)
        x0=x0-1
        y0=y0+1
      end
      
      x0=x
      y0=y
      while x0<s and y0>=0
        p=Pt.new(x0,y0)
        lstNo.push(p)
        x0=x0+1
        y0=y0-1
      end
      
      while(lstNo.length>0)
        p=lstNo.pop
        if(p.y==lst[p.x])
          return false
        end
      end
      
      return true
  end
    
  def findQueen(lst,s,x) 
      
      if(x>=s)
        @v=@v+1
        puts("]>>solution No."+@v.to_s)
        pp lst
        return
      end
      
      for y in 0..s-1 do
        if(canSetQueen(lst,s,x,y))
          lst.push(y)   
          findQueen(lst,s,x+1)
          lst.pop
        end
      end
       
    end
end

class Pt
  attr_accessor:x
  attr_accessor:y
  def initialize(x,y)
      @x=x
      @y=y
  end
end

test.rb

require "pp"
require "./Queen.rb"

len = 8
lst = Array.new()

q=Queen1.new
q.findQueen(lst,len,0)

puts("end")

Leave a Reply

Your email address will not be published. Required fields are marked *

*