← Amazon questions

Minimum Moves to Emergency Exit in Grid

Filed under Amazon

Free read 3 of 3

Confirm 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

  1. Confirm grid dimensions and how unreachable persons should be represented in the result.

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.