← Questions

Shortest path in a grid with obstacles

0
AmazonCodingLast asked Dec 2025

A coding interview question asked in Amazon's coding round, last asked Dec 2025. It tests bfs, grids and shortest path.

A maze is an m × n grid where each cell is empty (0) or blocked (1). Given a start cell and an end cell, return the length of the shortest path between them, moving up, down, left or right, never into a blocked cell or off the grid. Return -1 if no path exists.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • shortest_path(grid: list[list[int]], start: tuple[int, int], end: tuple[int, int]) -> int — the number of moves; 0 when start == end.

Example

grid = [[0, 0, 0],
        [0, 1, 0],
        [0, 0, 0]]
shortest_path(grid, (0, 0), (2, 2))          ->  4
# (0,0) -> (1,0) -> (2,0) -> (2,1) -> (2,2), around the blocked centre

shortest_path([[0, 1], [1, 0]], (0, 0), (1, 1))   ->  -1
# the two open cells only touch diagonally

Constraints

  • 1 <= m, n <= 1000.
  • The start and end cells are empty.
  • No diagonal moves.

Clarifying questions

  • Can I modify the grid to mark visited cells?
  • Are diagonal moves allowed? (No.)
  • Should I return the path itself or only its length?

What a strong answer covers

  • Breadth-first search from the start, and why it gives the shortest path: it visits cells in order of distance, so the first time it reaches the end is with the fewest moves. Depth-first search does not.
  • Marking a cell visited when it is enqueued, so each cell enters the queue once: O(m · n) time and space.
  • Start equal to end, an unreachable end, and a 1000 × 1000 grid without recursion.
  • Bidirectional BFS, which explores far fewer cells on large open grids.

Follow-ups

  • Return the path, not just its length.
  • You may remove up to k obstacles.
  • Moves have different costs. Use Dijkstra's algorithm, or A* with a Manhattan-distance heuristic.

Where it's asked

  • Amazon · Coding · Last asked Dec 202555 min · Usually two rounds; one is often an object-oriented design built in steps · No AI

What it tests

bfs · grids · shortest path

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding