first_search.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. # ----------
  2. # User Instructions:
  3. #
  4. # Define a function, search() that returns a list
  5. # in the form of [optimal path length, row, col]. For
  6. # the grid shown below, your function should output
  7. # [11, 4, 5].
  8. #
  9. # If there is no valid path from the start point
  10. # to the goal, your function should return the string
  11. # 'fail'
  12. # ----------
  13. # Grid format:
  14. # 0 = Navigable space
  15. # 1 = Occupied space
  16. from collections import deque
  17. import numpy as np
  18. grid = np.array([[0, 0, 1, 0, 0, 0, 0],
  19. [0, 0, 1, 0, 1, 0, 1],
  20. [0, 0, 1, 0, 0, 0, 0],
  21. [0, 0, 1, 1, 1, 0, 0],
  22. [0, 0, 0, 0, 1, 0, 1]])
  23. init = np.array([0, 0])
  24. # goal = np.array([len(grid)-1, len(grid[0])-1])
  25. goal = np.array([3, 6])
  26. cost = np.array([1.0, 1.0, 1.0, 1.0])
  27. delta = np.array([[-1, 0], # go up
  28. [0, -1], # go left
  29. [1, 0], # go down
  30. [0, 1]]) # go right
  31. delta_name = ['^', '<', 'v', '>']
  32. def check_navigable(goal) -> bool:
  33. if all(goal >= np.array([0, 0])) and all(goal <= np.array([len(grid)-1, len(grid[0])-1])):
  34. # print("G: ",goal)
  35. if not grid[goal[0], goal[1]]:
  36. return True
  37. return False
  38. def search(grid: np.ndarray, init: list, goal: list, cost: list):
  39. # ----------------------------------------
  40. # insert code here
  41. # ----------------------------------------
  42. path = list()
  43. next_check = deque()
  44. next_check.append(init)
  45. already_checked = dict()
  46. already_checked[tuple(init)] = 0
  47. cost_map = np.zeros([len(grid), len(grid[0])])
  48. extend_map = np.zeros([len(grid), len(grid[0])]) - 1
  49. extend_now = 0
  50. extend_map[0,0] = extend_now
  51. while next_check:
  52. checking = next_check.popleft()
  53. if check_navigable(checking):
  54. for move in delta:
  55. next = checking+move # type: np.ndarray
  56. if check_navigable(next) and tuple(next) not in already_checked:
  57. extend_now += 1
  58. next_check.append(next)
  59. cost_now = already_checked[checking[0], checking[1]]+1
  60. already_checked[tuple(next)] = cost_now
  61. cost_map[next[0], next[1]] = cost_now
  62. extend_map[next[0], next[1]] = extend_now
  63. if all(next == goal):
  64. print(cost_map)
  65. print(extend_map)
  66. return [cost_now, next[0], next[1]]
  67. print(cost_map)
  68. print(extend_map)
  69. return "fail"
  70. print(search(grid, init, goal, cost))