CS188-Pacman P1 Search Q2 BFS

CS188 | Introduction to Artificial Intelligence

Spring 2020

Project 1 Search

Q2: Breadth First Search

本题要求与上题几乎一致,唯一区别在于搜索算法由DFS更改为BFS
CS188-Pacman P1 Search Q2 BFS_第1张图片

伪代码与上题一致,唯一需要更改的点在于,BFS采用先入先出的策略,因此应该选择队列结构来实现fringe
具体实现代码如下:

def breadthFirstSearch(problem):
    """Search the shallowest nodes in the search tree first."""
    "*** YOUR CODE HERE ***"
    temp = problem.getStartState()
    found = []
    fringe = util.Queue()
    fringe.push((temp,[]))
    while not fringe.isEmpty():
        temp, path = fringe.pop()
        if problem.isGoalState(temp):
            return path
        if not temp in found:
            found.append(temp)
            for child in problem.getSuccessors(temp):
                if child[0] not in found:
                    fringe.push((child[0], path + [child[1]]))
    
    util.raiseNotDefined()

转载请注明作者及来源

你可能感兴趣的:(人智导作业)