递归:在深度优先搜索中,孩子被添加到错误的父对象中

2024-10-04 03:19:47 发布

您现在位置:Python中文网/ 问答频道 /正文

.getSuccessorStates(node)返回正确的继承状态(子级)。我已经使用这个问题中提供的图单独测试了这个方法。问题在于,当我将递归添加到这个迭代深化深度优先搜索算法的混合中时。当我在返回所有内容后检查self.parent字典的值以便回溯并找到最短路径时,字典中的某些节点与不正确的父节点匹配。我99%确定它与我存储self[parent] = node时的递归有关,因为getSuccessorStates为给定节点提供了正确的子节点,但是self.parent包含一些具有错误的父到子匹配的值。我想知道我是否把self.parent[child] = node放错了地方?你知道吗

def __init__(self, graph):
        self.graph = graph
        self.nodesCreated = 0
        self.maxFrontier = 0
        self.maxExplored = 0
        self.parent = {}

def recursive_depth_limited_search(self, node, limit):
    if node == self.getGraph().getGoalState():
        return node
    elif limit == 0:
        return "cutoff"
    else:
        cutoff_occurred = False
        for child in self.getGraph().getSuccessorStates(node):
            self.setNodesCreated(self.getNodesCreated() + 1)
            self.parent[child] = node
            result = self.recursive_depth_limited_search(child, limit - 1)
            if result == "cutoff":
                cutoff_occurred = True
            elif result != "No solution found":
                return result
        if cutoff_occurred:
            return "cutoff"
        else:
            return "No solution found"

Tags: selfnodechildreturnif字典节点def