first_search.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. [1, 0, 0, 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: list, 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. while next_check:
  49. checking = next_check.popleft()
  50. if check_navigable(checking):
  51. # already_checked[tuple(checking)] =
  52. for move in delta:
  53. next = checking+move # type: np.ndarray
  54. if check_navigable(next) and tuple(next) not in already_checked:
  55. next_check.append(next)
  56. cost_now = already_checked[checking[0], checking[1]]+1
  57. already_checked[tuple(next)] = cost_now
  58. cost_map[next[0], next[1]] = cost_now
  59. if all(next == goal):
  60. print(cost_map)
  61. return [cost_now, next[0], next[1]]
  62. print(cost_map)
  63. return "fail"
  64. print(search(grid, init, goal, cost))