Minimum Moves to Emergency Exit in Grid
Filed under Amazon
Free read 3 of 3Confirm grid dimensions and how unreachable persons should be represented in the result.
The question
Given a 2D grid containing Persons ('P'), Walls ('W'), and Emergency Exits ('E'), calculate the minimum number of moves for each person to reach their nearest emergency exit. If a person cannot reach an exit, output -1 for that person.
Constraints
- m == grid.length
- n == grid[i].length
- 1 <= m, n <= 100
Examples
- Input
- grid = [['P','W','E']]
- Output
- [[2]]
- Why
- Person at (0,0) takes 2 steps to reach exit at (0,2).
Approach
Confirm grid dimensions and how unreachable persons should be represented in the result.
Run a separate BFS from each person cell to find the closest exit, resulting in O(M^2 * N^2) time.
Multi-source BFS: Start the queue with all Emergency Exits ('E') simultaneously and propagate shortest distances outward to persons ('P').
No exits in the grid, grid filled entirely with walls.
Tips
- What they are testing: Test grids with multiple exits, blocked paths (surrounded by walls), and no exits.
- Common mistake: Running BFS from every person individually, leading to Time Limit Exceeded (TLE).
Related Amazon questions
Collected from public candidate posts and coding forums. Updated Nov 2026.