皇后问题的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)
- 皇后问题的Ruby实现
- 八皇后问题的实现
- N皇后问题的实现
- 八皇后问题的实现
- 八皇后问题的java实现
- 八皇后问题动态图形的实现
- 八皇后问题的java 实现
- 八皇后问题的java实现
- 八皇后问题的c++实现
- 八皇后问题的算法实现
- 八皇后问题的C语言实现
- 八皇后问题的C++实现
- N皇后问题的回溯法实现
- N皇后问题的递归回溯实现
- Java实现经典八皇后的问题
- 八皇后问题的个人实现
- N皇后问题的简单实现
- java实现八皇后的排列问题
- 又写短信接口
- rfc2462
- rfc2464
- 1,000,000-艰苦奋斗,勤俭持家
- tomcat集群配置(转贴)
- 皇后问题的Ruby实现
- 全国所有城市人均GDP排名(包含县级市 611 )
- 2005全国百强县
- 如何获取SQL Server数据库里表的占用容量大小
- [BlackBox项目]Moodle用户分析
- Tomcat的RemoteAddrValve的使用
- 其实我真的很忙
- 有关英语学习的一点体会(原创)-----欢迎大家拍砖
- 创建有个性的对话框之ATL/WTL篇