Demolition Robot
Filed under Amazon
Free read 3 of 3Identify the starting coordinates and ensure the grid dimensions are valid.
The question
Given a matrix representing a grid with trenches (0), flat paths (1), and an obstacle/destination (9), find the minimum distance to reach the obstacle from the starting position using breadth-first search.
Constraints
- Can only move up, down, left, or right through flat paths (1).
- Trenches (0) are impassable.
Examples
- Input
- grid = [[1, 0, 0], [1, 1, 9], [0, 0, 0]]
- Output
- 3
- Why
- Shortest path from (0,0) to (1,2) navigating through 1s takes 3 steps.
Approach
Identify the starting coordinates and ensure the grid dimensions are valid.
Explore all possible paths using recursive DFS and track the minimum path length.
Use BFS with a queue to explore layer by layer, tracking visited cells to find the shortest path in O(V + E) time.
Destination is blocked completely, or grid is single-celled.
Tips
- What they are testing: Test when no path exists to the destination, or when start is already at the destination.
- Common mistake: Using Depth-First Search instead of Breadth-First Search, which does not guarantee the shortest path.
Related Amazon questions
Collected from public candidate posts and coding forums. Updated Nov 2026.