骑士的Travail:递归解决方案

时间:2018-06-21 03:09:51

标签: ruby recursion binary-tree binary-search-tree knights-tour

问题是要创建一个数据结构,类似于二进制搜索树,该树可以列出骑士(在国际象棋中)在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。我的猜测是我的递归正在经历无限循环,但是我看不到问题所在。预先感谢!

1 个答案:

答案 0 :(得分:0)

我看不到您实际上终止搜索的任何方式。您可以修剪它是否离开板,但是您需要人为地将其限制为64(板上的正方形数)和/或跟踪其已访问的位置,而不能再次访问该正方形。

相关问题