Compute grid shortest path with obstacles
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of grid-based graph traversal, shortest-path reasoning, and obstacle handling, testing competence in algorithmic problem-solving and complexity analysis within the Coding & Algorithms domain.
Constraints
- 1 <= m, n <= 1000
- Each cell is either -1 (obstacle) or a non-negative integer (traversable)
- Only up/down/left/right moves are allowed
- Path length is counted as the number of moves (edges), so a single-cell start==goal grid has length 0
Examples
Input: [[0,0,0],[0,-1,0],[0,0,0]]
Expected Output: 4
Explanation: The center is blocked; the shortest path goes around it in 4 moves, e.g. (0,0)->(0,1)->(0,2)->(1,2)->(2,2).
Input: [[0,-1],[-1,0]]
Expected Output: -1
Explanation: Both neighbors of the start are obstacles, so the goal at (1,1) is unreachable.
Input: [[0]]
Expected Output: 0
Explanation: Single-cell grid: the start is already the goal, so zero moves are needed.
Input: [[-1,0],[0,0]]
Expected Output: -1
Explanation: The start cell (0,0) is itself an obstacle, so return -1.
Input: [[0,0],[0,-1]]
Expected Output: -1
Explanation: The goal cell (1,1) is an obstacle, so it can never be reached.
Input: [[0,0,0,0],[0,0,0,0]]
Expected Output: 4
Explanation: Open 2x4 grid: shortest path from (0,0) to (1,3) is 4 moves (3 right + 1 down).
Input: [[0,1,2],[3,4,5],[6,7,8]]
Expected Output: 4
Explanation: All cells traversable (only -1 is an obstacle); Manhattan distance from (0,0) to (2,2) is 4.
Hints
- Every move costs the same (unit weight), so BFS from the start yields shortest paths — Dijkstra is unnecessary.
- Mark a cell visited the moment you enqueue it, not when you dequeue it, to avoid adding the same cell multiple times.
- Handle the special cases first: empty grid, blocked start, blocked goal, and a 1x1 grid (answer 0).