DFS的实现:
Q1:
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 ***"
fringe = util.Stack()
start = problem.getStartState()
fringe.push((start, 0, []))
closed = set()
while not fringe.isEmpty():
(node, cost, path) = fringe.pop()
if problem.isGoalState(node):
return path
if not node in closed:
closed.add(node)
for child_node, child_action, child_cost in problem.getSuccessors(node):
new_cost = cost + child_cost
new_path = path + [child_action]
new_state = (child_node, new_cost, new_path)
fringe.push(new_state)
Q2(改用Queue即可,没什么技术含量)
def breadthFirstSearch(problem):
"""Search the shallowest nodes in the search tree first."""
"*** YOUR CODE HERE ***"
fringe = util.Queue()
start = problem.getStartState()
fringe.push((start, 0, []))
closed = set()
while not fringe.isEmpty():
(node, cost, path) = fringe.pop()
if problem.isGoalState(node):
return path
if not node in closed:
closed.add(node)
for child_node, child_action, child_cost in problem.getSuccessors(node):
new_cost = cost + child_cost
new_path = path + [child_action]
new_state = (child_node, new_cost, new_path)
fringe.push(new_state)
注意观察util中的优先队列实现
依葫芦画瓢,就是加快版的BFS
def uniformCostSearch(problem):
"""Search the node of least total cost first."""
"*** YOUR CODE HERE ***"
fringe = util.PriorityQueue()
start = problem.getStartState()
fringe.push((start, 0, []), 0d)
closed = set()
while not fringe.isEmpty():
(node, cost, path) = fringe.pop()
if problem.isGoalState(node):
return path
if not node in closed:
closed.add(node)
for child_node, child_action, child_cost in problem.getSuccessors(node):
new_cost = cost + child_cost
new_path = path + [child_action]
new_state = (child_node, new_cost, new_path)
fringe.push(new_state, new_cost)
a*也就是改一下上面的cost
fringe = util.PriorityQueue()
start = problem.getStartState()
fringe.push((start, 0+heuristic(start, problem), []), 0)
closed = set()
while not fringe.isEmpty():
(node, cost, path) = fringe.pop()
if problem.isGoalState(node):
return path
if not node in closed:
closed.add(node)
for child_node, child_action, child_cost in problem.getSuccessors(node):
new_cost = cost + child_cost+heuristic(child_node, problem)
new_path = path + [child_action]
new_state = (child_node, new_cost, new_path)
fringe.push(new_state, new_cost)