我的DFS算法在回溯情况下无法正常工作

时间:2016-11-03 15:14:09

标签: python python-2.7

我有一个问题,我需要使用DFS来解决。到目前为止,这是我的功能,根据我提供的自动编程器,它可以在4/5测试中工作,但只能在回溯情况下失败:

def depthFirstSearch(problem):

    stack=Stack()
    if problem.isGoalState(start):
    return actions
while stack:
    parent=stack.pop()
    if flag==1:
            action=actionStack.pop()
    if parent in visited: continue
    visited.add(parent)
    if problem.isGoalState(parent):
                    while parent!=None:
                            actions.append(action)
                            parent=parentMap[parent]
                            action=actionMap[parent]
                    return actions
    children=problem.getSuccessors(parent)
    for child in children:
            stack.push(child[0])
            actionStack.push(child[1])
            parentMap[child]=parent
            if flag==1:
                    actionMap[child] = child[1]
    flag=1
util.raiseNotDefined()

getSuccessors返回三元组列表(状态,操作,成本),我需要返回一个操作列表,以指导代理从开始到目标。提前抱歉,我是python的新手。任何提示?

编辑:这是

失败的树

失败:test_cases / q1 / graph_backtrack.test     图:

     B   
     ^
     |
    *A --> C --> G
     |
     V
     D

    A is the start state, G is the goal.  Arrows mark 
    possible state transitions.  This tests whether
    you extract the sequence of actions correctly even
    if your search backtracks.  If you fail this, your
    nodes are not correctly tracking the sequences of
    actions required to reach them.
student solution:       ['2:A->D', '1:A->C', '0:C->G']
student expanded_states:    ['A', 'D', 'C']

correct solution:       ['1:A->C', '0:C->G']
correct expanded_states:    ['A', 'D', 'C']
correct rev_solution:       ['1:A->C', '0:C->G']
correct rev_expanded_states:    ['A', 'B', 'C']

1 个答案:

答案 0 :(得分:1)

你只有一套动作。不是每一步的行动。&#xA;如果你在7岁以下旅行,那么你的行动将是1,2,3,4,5,6,7,当它应该是1,2,3,6,7 < / p>&#XA;&#XA;

 <代码> 1-2-3-4-5&#XA; 0-0-6-0-0&#XA; 0-0-7-0-0& #xA;  
&#xA;&#xA;

不要害怕在每次下一步行动中打包当前状态。除非你有一个非常大的解决方案空间你应该没事。

&#xA;