CS188-Pacman P1 Search Q1 DFS

CS188 | Introduction to Artificial Intelligence

Spring 2020

Project 1 Search

Q1: Finding a Fixed Food Dot using Depth First Search

此题目要求使用深度优先搜索(DFS) 来完成吃豆人对食物的搜索,也就是完成search.py里的DFS功能。其原理较为简单,如下图笔记所示:
CS188-Pacman P1 Search Q1 DFS_第1张图片
参考伪代码如下:
CS188-Pacman P1 Search Q1 DFS_第2张图片
注意图搜索树搜索算法的区别(需不需要检索closed)
深度优先搜索要求满足先入后出的策略,因此fringe应选用栈来实现,可直接通过调用util.py里写好的栈结构来完成。
具体python代码实现如下:

def depthFirstSearch(problem):
    """
    Search the deepest nodes in the search tree first.

    Your search algorithm needs to return a list of actions that reaches the
    goal. Make sure to implement a graph search algorithm.

    To get started, you might want to try some of these simple commands to
    understand the search problem that is being passed in:

    print("Start:", problem.getStartState())
    print("Is the start a goal?", problem.isGoalState(problem.getStartState()))
    print("Start's successors:", problem.getSuccessors(problem.getStartState()))
    """
    "*** YOUR CODE HERE ***"
    
    temp = problem.getStartState()
    past = []
    fringe = util.Stack()
    fringe.push((temp, []))
    while not fringe.isEmpty():
        temp, path = fringe.pop()
        past.append(temp)
        if problem.isGoalState(temp):
            return path
        for child in problem.getSuccessors(temp):
            if child[0] not in past:
                fringe.push((child[0], path + [child[1]]))

    util.raiseNotDefined()

值得注意的是,这里以及接下来的几个问题的past(closed)均使用了列表,从原理上讲是不对的。因为图搜索算法需要频繁的检索当前展开节点是否已经被展开过了,即该节点是否在closed集中,这里如果使用set则可通过hash来达到O(1)的查找时间,这对于搜索算法是至关重要的。但由于本次作业数据量不大,就懒得改了。

转载请注明作者及来源

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