【发布时间】:2018-11-30 06:31:04
【问题描述】:
问题是要创建一个数据结构,类似于二叉搜索树,它可以列出一个马(在国际象棋中)在 8x8 棋盘上可以做出的所有可能动作。我想出了一个带有当前位置的单节点类,一个父节点和 8 个可能的子节点,代表骑士可以做出的 8 个可能的动作。
class KnightNode
attr_accessor :location, :child_1, :child_2, :child_4, :child_5, :child_7, :child_8, :child_10, :child_11
def initialize(location = nil)
@location = location
@parent = nil
#8 possible children, label them as if they were hands on a clock
@child_1 = nil
@child_2 = nil
@child_4 = nil
@child_5 = nil
@child_7 = nil
@child_8 = nil
@child_10 = nil
@child_11 = nil
end
end
def generate_tree(location)
root = KnightNode.new(location)
move1 = [root.location[0] + 1,root.location[1] + 2]
move2 = [root.location[0] + 2,root.location[1] + 1]
move4 = [root.location[0] + 2,root.location[1] - 1]
move5 = [root.location[0] + 1,root.location[1] - 2]
move7 = [root.location[0] - 1,root.location[1] - 2]
move8 = [root.location[0] - 2,root.location[1] - 1]
move10 = [root.location[0] - 2,root.location[1] - 1]
move11 = [root.location[0] - 1,root.location[1] + 2]
move1[0] > 7 && move1[1] > 7 ? root.child_1 = nil : root.child_1 = generate_tree(move1)
move2[0] > 7 && move2[1] > 7 ? root.child_2 = nil : root.child_2 = generate_tree(move2)
move4[0] > 7 && move4[1] < 0 ? root.child_4 = nil : root.child_4 = generate_tree(move4)
move5[0] > 7 && move5[1] < 7 ? root.child_5 = nil : root.child_5 = generate_tree(move5)
move7[0] < 0 && move7[1] < 7 ? root.child_7 = nil : root.child_7 = generate_tree(move7)
move8[0] < 0 && move8[1] < 0 ? root.child_8 = nil : root.child_8 = generate_tree(move8)
move10[0] < 0 && move10[1] < 0 ? root.child_10 = nil : root.child_10 = generate_tree(move10)
move11[0] < 0 && move11[1] > 7 ? root.child_11 = nil : root.child_11 = generate_tree(move11)
return root
end
generate_tree([3,3])
当我运行此代码时,我遇到了 SystemStackError。我的猜测是我的递归正在经历一个无限循环,但是我没有看到问题。提前致谢!
【问题讨论】:
标签: ruby recursion binary-tree binary-search-tree knights-tour