dfs.py 2.0 KB

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