dfs.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. @author: huiming zhou
  5. """
  6. import queue
  7. import environment
  8. import tools
  9. class DFS:
  10. """
  11. DFS -> Depth-first Searching
  12. """
  13. def __init__(self, Start_State, Goal_State, n, m):
  14. self.xI = Start_State
  15. self.xG = Goal_State
  16. self.u_set = environment.motions # feasible input set
  17. self.obs_map = environment.map_obs() # position of obstacles
  18. self.n = n
  19. self.m = m
  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. actions = {self.xI: (0, 0)} # record actions of nodes
  29. visited = []
  30. while not q_dfs.empty():
  31. x_current = q_dfs.get()
  32. visited.append(x_current) # record visited nodes
  33. if x_current == self.xG: # stop condition
  34. break
  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))]) # neighbor node
  37. # if neighbor node is not in obstacles and has not been visited -> ...
  38. if 0 <= x_next[0] < self.n and 0 <= x_next[1] < self.m \
  39. and x_next not in parent \
  40. and not tools.obs_detect(x_current, u_next, self.obs_map):
  41. q_dfs.put(x_next)
  42. parent[x_next] = x_current
  43. actions[x_next] = u_next
  44. [path_dfs, actions_dfs] = tools.extract_path(self.xI, self.xG, parent, actions)
  45. return path_dfs, actions_dfs, visited
  46. if __name__ == '__main__':
  47. x_Start = (15, 10) # Starting node
  48. x_Goal = (48, 15) # Goal node
  49. dfs = DFS(x_Start, x_Goal, environment.col, environment.row)
  50. [path_dfs, actions_dfs, visited_dfs] = dfs.searching()
  51. tools.showPath(x_Start, x_Goal, path_dfs, visited_dfs, 'depth_first_searching') # Plot path and visited nodes