heatherhb

A* Search

Nov 4th, 2011
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.52 KB | None | 0 0
  1. def aStarSearch(problem, heuristic=nullHeuristic):
  2.   "Search the node that has the lowest combined cost and heuristic first."
  3.  
  4.   solution = []
  5.  
  6.   if problem.isGoalState(problem.getStartState()):
  7.     return solution
  8.  
  9.   #initialize frontier and explored set
  10.   frontier = PriorityQueue()
  11.   for (loc, action, cost) in problem.getSuccessors(problem.getStartState()):
  12.     newNode = Node(loc, action, cost+heuristic(loc, problem), cost, None)
  13.     frontier.push(newNode, cost+heuristic(loc, problem))
  14.   explored = []
  15.  
  16.   #while the frontier is not empty, search
  17.   while (not frontier.isEmpty()):
  18.     curNode = frontier.pop()
  19.     if(curNode.getLoc() not in explored):
  20.       #if current node contains a goal state
  21.       if problem.isGoalState(curNode.getLoc()):
  22.         preNode = curNode
  23.         solution.append(preNode.getAction())
  24.         #while predecessor exists
  25.         while (preNode.getPred()):
  26.           preNode = preNode.getPred()
  27.           solution.append(preNode.getAction())
  28.         solution.reverse()
  29.         return solution
  30.       explored.append(curNode.getLoc())
  31.       for (loc, action, cost) in problem.getSuccessors(curNode.getLoc()):
  32.         #if location is not already explored, add to frontier
  33.         if(loc not in explored):
  34.           newNode = Node(loc, action, curNode.getPathCost()+cost+heuristic(loc, problem), curNode.getPathCost()+cost, curNode)
  35.           frontier.push(newNode, curNode.getPathCost()+cost+heuristic(loc, problem))
  36.  
  37.   #all nodes searched, frontier empty
  38.   return [] #failure
  39.  
Advertisement
Add Comment
Please, Sign In to add comment