皇后问题的Ruby实现

来源:互联网 发布:在家做淘宝客服可信吗 编辑:程序博客网 时间:2024/04/30 14:29

        人工智能课讲4皇后问题,数据结构做8皇后,索性棋盘大小可变,用100行的Ruby代码写了皇后问题的实现。

Queens.rb


class Queen
 @@Chessboard = nil
 
 def initialize(size)
  @@Chessboard = Array.new(size)
  puts "The chessboard is #{size} * #{@@Chessboard.size}./n"
  i = 0
  flag = FALSE
  while i < size do
   @@Chessboard[0] = i
   if putQueen(1)
    flag = TRUE
    break
   else
    @@Chessboard = Array.new(size)
   end
   i += 1
  end
  
  if flag
   printBoard()
  else
   puts "Can/'t find a solution./n"
  end
 end
  
 private
 def putQueen(line)
  flag = FALSE
  i = 0
  while i < @@Chessboard.size do
   @@Chessboard[line] = i
   if !check(line, i)
    i += 1
    @@Chessboard[line] = nil
    next
   end
   
   if line < @@Chessboard.size - 1
    if putQueen(line + 1)
     flag = TRUE
     break
    end
   else
    flag = TRUE
    break
   end
   i += 1
  end
  return flag
 end
 
 def check(row, col)
  flag = TRUE
  i = 0
  while i < @@Chessboard.size
   if @@Chessboard[i] == nil
    break
   end  
   if i == row
    i += 1
    next
   end
   if @@Chessboard[i] == col || (@@Chessboard[i] - col).abs == (row - i).abs
    flag = FALSE
    break
   end
   i += 1
  end
  return flag
 end
 
 def printBoard
  m = 0;
  while m < @@Chessboard.size
   n = 0
   while n < @@Chessboard[m]
    print 'X '
    n += 1
   end
   print 'Q '
   n = @@Chessboard[m]
   while n < @@Chessboard.size - 1
    print 'X '
    n += 1
   end
   print "/n"
   m += 1
  end
 end
end

print 'Please input the size of the chessboard(<10):'
a = gets
if a.to_i >= 10
 a = "8"
end
q = Queen.new(a.to_i)

原创粉丝点击