dfs.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import os
  2. import sys
  3. import math
  4. import heapq
  5. sys.path.append(os.path.dirname(os.path.abspath(__file__)) +
  6. "/../../Search_based_Planning/")
  7. from Search_2D import plotting, env
  8. from Search_2D.Astar import AStar
  9. class DFS(AStar):
  10. """DFS add the new visited node in the front of the openset
  11. """
  12. def searching(self):
  13. """
  14. Breadth-first Searching.
  15. :return: path, visited order
  16. """
  17. self.PARENT[self.s_start] = self.s_start
  18. self.g[self.s_start] = 0
  19. self.g[self.s_goal] = math.inf
  20. heapq.heappush(self.OPEN,
  21. (0, self.s_start))
  22. while self.OPEN:
  23. _, s = heapq.heappop(self.OPEN)
  24. self.CLOSED.append(s)
  25. if s == self.s_goal:
  26. break
  27. for s_n in self.get_neighbor(s):
  28. new_cost = self.g[s] + self.cost(s, s_n)
  29. if s_n not in self.g:
  30. self.g[s_n] = math.inf
  31. if new_cost < self.g[s_n]: # conditions for updating Cost
  32. self.g[s_n] = new_cost
  33. self.PARENT[s_n] = s
  34. # dfs, add new node to the front of the openset
  35. prior = self.OPEN[0][0]-1 if len(self.OPEN)>0 else 0
  36. heapq.heappush(self.OPEN, (prior, s_n))
  37. return self.extract_path(self.PARENT), self.CLOSED
  38. def main():
  39. s_start = (5, 5)
  40. s_goal = (45, 25)
  41. dfs = DFS(s_start, s_goal, 'None')
  42. plot = plotting.Plotting(s_start, s_goal)
  43. path, visited = dfs.searching()
  44. visited = list(dict.fromkeys(visited))
  45. plot.animation(path, visited, "Depth-first Searching (DFS)") # animation
  46. if __name__ == '__main__':
  47. main()