【问题标题】:Knight's Travail: Recursive SolutionKnight's Travail:递归解决方案
【发布时间】: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


    【解决方案1】:

    我没有看到您实际终止搜索的任何方式。如果它离开棋盘,则进行修剪,但您需要人为地将其限制为 64(棋盘上的方格数)和/或跟踪它已经访问过的位置,并且不要让它再次访问该方格。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-22
      • 2015-10-25
      • 1970-01-01
      • 2021-11-03
      • 2018-12-30
      • 2020-06-07
      • 2015-06-26
      • 1970-01-01
      相关资源
      最近更新 更多