我正在尝试创建具有众所周知的滑动拼图的不同可能状态的树
如果你不知道,它是这样的:
[3 5 2]
[4 1]
[8 6 7]
你必须在哪里做到这一点:
[1 2 3]
[4 5 6]
[7 8 ]
基本上,每个状态都会生成新状态,具体取决于如何移动空白空间(向上、向下、向左或向右)
我想要的是创建树,所有状态都将根作为拼图的初始状态,但是当向树添加子(新状态)时,它应该检查该状态是否已经添加到树中的任何位置
你介意帮我实现吗?提前致谢 :)
这是我当前的代码RecursionError: maximum recursion depth exceeded while calling a Python object
节点类:
class Node(object):
def __init__(self, value, parent=None):
self.parent = parent
self.value = value
self.children = []
def append(self, obj):
if obj is not self.parent and obj not in self.children and obj is not None:
self.children.append(obj)
def has_children(self):
return len(self.children) > 0
def __iter__(self):
yield self.value
for v in chain(*map(iter, self.children)):
yield v
def find_root(self):
p = self
while p.parent is not None:
p = p.parent
return p
树生成方法(认为self
是拼图状态):
def to_tree(self, parent=None):
values = []
if parent is not None:
for child in parent.find_root():
values.append(child)
value = nd.Node(self, parent)
if value not in values:
children = [move[1].to_tree(value) for move in self.get_possible_movements()]
for child in children:
if child is not None:
value.append(child)
return value
else:
return None