bfs.py 1.7 KB

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