Advertisement
Guest User

Untitled

a guest
Sep 15th, 2019
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. def bfs(maze):
  2. """
  3. Runs BFS for part 1 of the assignment.
  4.  
  5. @param maze: The maze to execute the search on.
  6.  
  7. @return path: a list of tuples containing the coordinates of each state in the computed path
  8. """
  9. # TODO: Write your code here
  10.  
  11. backtrack_dict = {}
  12. q = queue.Queue(maxsize=0)
  13. explored_list = []
  14.  
  15. start = maze.getStart()
  16. q.put(start)
  17. backtrack_dict[start] = None #the parent of start is none
  18.  
  19. while (not q.empty()):
  20. curr_point = q.get()
  21.  
  22. if maze.isObjective(curr_point[0], curr_point[1]):
  23. path = []
  24. path.append(curr_point)
  25. parent = backtrack_dict.get(curr_point)
  26.  
  27. while (parent != None): #loop through each point in path getting the previous point
  28. path.append(parent)
  29. curr_point = parent
  30. parent = backtrack_dict.get(curr_point)
  31.  
  32. path.reverse() #flip the list to start from start
  33. print(path)
  34. return path
  35.  
  36. else: #if the point is not the final goal
  37. if curr_point not in explored_list:
  38. explored_list.append(curr_point)
  39. neighbors = maze.getNeighbors(curr_point[0], curr_point[1])
  40. for neighbor in neighbors:
  41. if neighbor not in explored_list:
  42. q.put(neighbor)
  43. backtrack_dict[neighbor] = curr_point
  44.  
  45.  
  46. return []
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement