dfs.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. @author: huiming zhou
  5. """
  6. import queue
  7. import tools
  8. import env
  9. import motion_model
  10. class DFS:
  11. """
  12. DFS -> Depth-first Searching
  13. """
  14. def __init__(self, x_start, x_goal, x_range, y_range):
  15. self.u_set = motion_model.motions # feasible input set
  16. self.xI, self.xG = x_start, x_goal
  17. self.x_range, self.y_range = x_range, y_range
  18. self.obs = env.obs_map() # position of obstacles
  19. env.show_map(self.xI, self.xG, self.obs, "depth-first searching")
  20. def searching(self):
  21. """
  22. Searching using DFS.
  23. :return: planning path, action in each node, visited nodes in the planning process
  24. """
  25. q_dfs = queue.QueueLIFO() # last-in-first-out queue
  26. q_dfs.put(self.xI)
  27. parent = {self.xI: self.xI} # record parents of nodes
  28. action = {self.xI: (0, 0)} # record actions of nodes
  29. while not q_dfs.empty():
  30. x_current = q_dfs.get()
  31. if x_current == self.xG:
  32. break
  33. if x_current != self.xI:
  34. tools.plot_dots(x_current, len(parent))
  35. for u_next in self.u_set: # explore neighborhoods of current node
  36. x_next = tuple([x_current[i] + u_next[i] for i in range(len(x_current))])
  37. if x_next not in parent and x_next not in self.obs: # node not visited and not in obstacles
  38. q_dfs.put(x_next)
  39. parent[x_next] = x_current
  40. action[x_next] = u_next
  41. [path_dfs, action_dfs] = tools.extract_path(self.xI, self.xG, parent, action)
  42. return path_dfs, action_dfs
  43. if __name__ == '__main__':
  44. x_Start = (5, 5) # Starting node
  45. x_Goal = (49, 5) # Goal node
  46. dfs = DFS(x_Start, x_Goal, env.x_range, env.y_range)
  47. [path_dfs, action_dfs] = dfs.searching()
  48. tools.showPath(x_Start, x_Goal, path_dfs)