Find shortest path in a grid with obstacles
AmazonApplied Scientist · OnsiteLast updated
This question evaluates understanding of pathfinding in grid-based environments, graph traversal concepts, and algorithmic complexity when navigating obstacles and boundary constraints in an unweighted 2D search space.
You are given a 2D grid of size m x n representing a maze. Each cell in the grid is either empty (0) or blocked (1).
You are also given two coordinates:
start = (sx, sy)end = (ex, ey)
You can move from a cell to its 4-directional neighbors (up, down, left, right), but you cannot move into or through blocked cells, and you must remain inside the grid.
Return the length of the shortest path (in number of steps) from start to end. If there is no valid path, return -1.
Assumptions and details:
0 <= sx, ex < m0 <= sy, ey < ngrid[sx][sy] == 0andgrid[ex][ey] == 01 <= m, n <= 10^3- Time complexity should be efficient for the upper bounds (you may consider BFS or DFS-based approaches).
Input format (for reference):
m, n(integers)gridas anm x nmatrix of 0s and 1sstartcoordinateendcoordinate
Output:
- An integer representing the length of the shortest path, or
-1if unreachable.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.