Compute grid shortest path with obstacles
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Overview: 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.
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).