Advertisement
Guest User

Untitled

a guest
Nov 20th, 2019
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | None | 0 0
  1. def depthFirstSearch(problem):
  2. stack, visited = [(problem.getStartState(), [])], []
  3. while stack:
  4. vertex, path = stack.pop()
  5. visited.append(vertex)
  6.  
  7. if problem.isGoalState(vertex):
  8. return path
  9. else:
  10. successors = problem.getSuccessors(vertex)
  11. for successor in successors:
  12. nextVertex, action, cost = successor
  13. if nextVertex not in visited:
  14. stack.append((nextVertex, path + [action]))
  15. return []
  16.  
  17. def breadthFirstSearch(problem):
  18. queue = util.Queue()
  19. queue.push( (problem.getStartState(),[]))
  20. visited = []
  21.  
  22. while not queue.isEmpty() :
  23. node, actions = queue.pop()
  24. if (problem.isGoalState(node)):
  25. return actions
  26. if not node in visited:
  27. visited.append(node)
  28. for child, derection, cost in problem.getSuccessors(node):
  29. queue.push((child,actions+[derection]))
  30. return []
  31.  
  32. def uniformCostSearch(problem):
  33. queue = util.PriorityQueue()
  34. queue.push((problem.getStartState(), [], 0), 0)
  35. visited = []
  36.  
  37. while not queue.isEmpty():
  38. node, actions, cur_cost = queue.pop()
  39.  
  40. if (problem.isGoalState(node)):
  41. return actions
  42. if not node in visited :
  43. visited.append(node)
  44. for child, direction, cost in problem.getSuccessors(node):
  45. queue.push((child, actions+[direction], cur_cost+cost), cur_cost+cost)
  46. return []
  47.  
  48.  
  49. def aStarSearch(problem, heuristic=nullHeuristic):
  50. queue = util.PriorityQueue()
  51. queue.push((problem.getStartState(), [], 0),heuristic(problem.getStartState(),problem) )
  52. visited = []
  53.  
  54. while not queue.isEmpty():
  55. node, actions, cur_cost = queue.pop()
  56. if (problem.isGoalState(node)):
  57. return actions
  58. if not node in visited:
  59. visited.append(node)
  60. for child, direction, cost in problem.getSuccessors(node):
  61. g= cur_cost + cost
  62. queue.push((child, actions+[direction], g),g+heuristic(child,problem) )
  63. return []
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement