Minimum Moves to Escape a Grid Before Moving Danger Sources Catch You
Company: ByteDance
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Overview: Find the minimum number of moves a person needs to reach the border of a walled grid while danger sources chase them, or return -1 when every route gets caught. It tests shortest-path reasoning with two competing arrival times per cell, a strict tie rule and edge cases such as starting on the border.
Constraints
- 1 <= len(grid) <= 500 and 1 <= len(grid[0]) <= 500, and every row has the same length.
- Every character is one of '.', '#', 'S' and 'D'.
- There is exactly one 'S' and zero or more 'D'.
- When an answer exists it is less than len(grid) * len(grid[0]), which fits in a 32-bit signed integer.
Examples
Input: (['S'],)
Expected Output: 0
Explanation: 1x1 grid: the start is on the border, so the answer is 0.
Input: (['SD'],)
Expected Output: 0
Explanation: Single row of 2 cells: the start is on the border even with a danger source right next to it.
Hints
- Standing on a cell only gets riskier as the minutes pass, so reaching a cell as early as possible is never worse than reaching it later.
- The earliest minute a danger source can occupy a cell depends only on the grid, so it can be compared with the minute the person would arrive there.
- A start on the border answers 0 right away, even with a danger source next to it.