search.py 文件源码

python
阅读 31 收藏 0 点赞 0 评论 0

项目:AIclass 作者: mttk 项目源码 文件源码
def constrainedBreadthFirstSearch(problem, legalStates):
    """
    A breadth-first search that finds a shortest path to a 
    state going only through given states.
    """
    # we need a set to remember all visited states
    visitedStates = set()

    # DFS works in LIFO fashion
    searchQueue = Queue()

    # add an initial state so the stack is not empty
    startState = problem.getStartState()
    startNode = SearchNode(startState)
    searchQueue.push(startNode)

    # iterate until completion
    while not searchQueue.isEmpty():
        currentNode = searchQueue.pop()
        currentState = currentNode.position

        # check for end
        if problem.isGoalState(currentState):
            return currentNode.backtrack()

        if currentState in visitedStates: 
            continue

        visitedStates.add(currentState)

        for futureState, move, _ in problem.getSuccessors(currentState):
            if futureState not in visitedStates and futureState in legalStates: 
                futureNode = SearchNode(futureState, parent=currentNode, transition=move)
                searchQueue.push(futureNode)

    print "Search finished, final state not found!"
    return
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号