python - 为什么我的深度优先搜索实现失败

标签 python algorithm depth-first-search

我一直在尝试不同的方法来实现深度优先搜索。我找到了一些工作方式,但它们涉及一些相当繁琐的字典工作。我开发了一个使用列表的新想法,但此实现返回的操作与期望的结果不匹配。我会尽可能清楚地注释代码:

start = problem.getStartState()            ## returns an (x, y) tuple
children = problem.getSuccessors(start)    ##returns the children of a parent node in ((start                  
                                           state), action, cost) format. 
stack = Stack()                            ##creates a Stack (LIFO) data structure
visited = []                               ##list of visited nodes
visited.append(start)
for child in children:
    stack.push((child, [], [], 0))         ##push children to fringe in the format of (child,
    while stack:                           ##path taken, actions taken, cost) 
        parent = stack.pop()
        node = parent[0]
        if parent[0] in visited: continue
        visited.append(parent[0])
        path = parent[1] + [node[0]]           ##assigns previous path/actions/cost to new 
        actions = parent[2] + [node[1]]        ##node, creating a cumulative, ordered list of
        print actions                          ##the path/actions and a cumulative cost
        cost = parent[3] + node[2]
        if problem.isGoalState(node[0]):
            print parent[2]
            return parent[2]                    ## returns list of actions 
        children = problem.getSuccessors(node[0])
        if children != []:
            for child in children:
                stack.push((child, path, actions, cost))   ##assigns cumulative lists to child

有人看到我的问题可能出在这个实现中吗?顺便说一句,我知道 DFS 在大多数情况下是一种低效的算法。但是一旦我正确地实现了这个实现,它应该能够通过简单地更改存储父节点的子节点的数据结构来交叉到其他搜索算法。

最佳答案

CS188 pal :D 在这里阅读你的代码真的很难......所有这些索引 % 使用更多的变量,它会更清楚。 我的解决方案:

def depthFirstSearch(problem):
    fringe = util.Stack()
    expanded = set()
    fringe.push((problem.getStartState(),[],0))
    
    while not fringe.isEmpty():
        curState, curMoves, curCost = fringe.pop()
        
        if(curState in expanded):
            continue
        
        expanded.add(curState)
        
        if problem.isGoalState(curState):
            return curMoves
        
        for state, direction, cost in problem.getSuccessors(curState):
            fringe.push((state, curMoves+[direction], curCost))
    return []

我希望我不需要评论它。这很容易阅读 :) 祝你有美好的一天;)

关于python - 为什么我的深度优先搜索实现失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12916700/

相关文章:

algorithm - 如何检测无向图是否有环并使用BFS或DFS输出

javascript - 如何从没有目的地的给定节点创建路径

python - 这在逻辑上是一样的吗?

python - 如何使用 SQLAlchemy 访问 AS/400?

python - 更新 pandas 数据框(具有复杂条件的元素的部分总和)的最快方法

algorithm - 构造函数参数还是方法参数?

c - 实现深度优先搜索时出错

python - 使用抽象语法树修改 Python 3 代码

python - 我们还应该为 ZipFile.open 捕获什么异常

java - 分而治之最大连续子数组 (MCS) 问题