8个难题的DFS算法什么都不返回?

问题描述

因此,我一直在尝试使用深度优先搜索解决第8个难题,其目的是获得最少的步骤(我知道DFS不是最合适的方法,但它是用于分配任务的)。

我尝试做一些函数(我不知道这是否可以,或者我是否应该为每个状态创建一个带有属性的类),像这样:

import sys
sys.setrecursionlimit(10**9) 

directionDict = {   0: [1,3],1: [0,2,4],2: [1,5],3: [0,4,6],4: [1,3,5,7],5: [2,8],6: [3,7: [4,6,8: [5,7]
                }

_explored = []

def depthFirst(currentState,goalState,explored,steps):
    if currentState == goalState:
        return (steps,'Done')
    else:   
        finalSteps = (100000000,'No State to Chose From')                  
        successorStates = findSuccessorStates(currentState) #gives the possible state possibilities
        successorStates = set(successorStates) - set(explored)
        
        for state in successorStates:
            if state not in explored:
                print(state)
                exploredcopy = explored.copy()
                exploredcopy.append(state)
                stepscopy = steps + 1
                result = (depthFirst(state,exploredcopy,stepscopy)[0],state)
                if result[0] < finalSteps[0]:
                    finalSteps = result

        return finalSteps
        
def findSuccessorStates(currentState):
    successorStates = []
    blankIndex = currentState.find("_") # index of the blank 
    successorStatesPos = directionDict[blankIndex]  # indexes of position to switch for the successor states
    for pos in successorStatesPos:
        currentStatecopy = list(currentState)
        currentStatecopy[blankIndex] = currentStatecopy[pos]
        currentStatecopy[pos] = "_"
        currentStatecopy = "".join(currentStatecopy)
        successorStates.append(currentStatecopy)
    return successorStates

问题是,当我运行代码时,它会持续运行几秒钟,然后停止,而不会返回任何内容。我已经增加了递归限制,所以很困惑。

有趣的是,当我对可以作为基本案例的步骤数进行限制时,代码永远不会停止(对于一步式回答,它会持续10分钟以上,除非那是这样的)成为):

else if steps >100:
    return (steps,'Done')

这是我在for循环中打印状态时发生的情况。

enter image description here

有人对如何解决这个问题有任何想法吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)