Question
(I need help with these problems; an explanation would be appreciated. In Python, please, thank you.) Perseverance is able to perform some science thanks to
(I need help with these problems; an explanation would be appreciated. In Python, please, thank you.)
Perseverance is able to perform some science thanks to you. It now spots a sector that has obstacles represented by 1s. Keeping the assumptions same as Q3, return the length of the shortest path avoiding obstacles. Return -1 if no such path exists.
Hints:
Dont explore neighboring cells that dont exist (are beyond the grids boundary)
Dont explore neighboring cells that are obstacles.
Dont revisit a cell.
Your search ends when there is nothing to explore.
You will have to propagate the information of the explored length so far.
Here are some examples.
grid = [[0,0,0],
[1,1,0],
[1,1,0]]
start, goal = (1,2), (0,0)
Solution = 4
grid = [[0,1],
[1,0]]
start, goal = (0, 0), (1,1)
Solution = -1 ---> Perseverance cant travel diagonally and thus there doesnt exist any feasible path.
####CODE
def shortest_path_grid(grid, start, goal):
'''
Function that returns the length of the shortest path in a grid
that HAS obstacles represented by 1s. The length is simply the number
of cells on the path including the 'start' and the 'goal'
:param grid: list of lists (represents a square grid where 0 represents free space and 1s obstacles)
:param start: tuple of start index
:param goal: tuple of goal index
:return: length of path
'''
n = len(grid)
if __name__ == "__main__":
grid = [[0,0,0],
[1,1,0],
[1,1,0]]
start, goal = (1,2), (0,0)
print(shortest_path_grid(grid, start, goal))
assert shortest_path_grid(grid, start, goal) == 4
grid = [[0,1],
[1,0]]
start, goal = (0, 0), (1,1)
print(shortest_path_grid(grid, start, goal))
assert shortest_path_grid(grid, start, goal) == -1
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started