Quick 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.

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

A rectangular grid contains open cells, walls, one person and any number of danger sources. Each minute the person moves to an edge-adjacent open cell, and the danger sources move through open cells at the same speed, chasing the person. The person wants to reach the border of the grid (any cell in the first or last row, or in the first or last column) before the danger sources can catch them. Return the minimum number of moves the person needs to stand safely on a border cell, or `-1` if no safe route exists. ### Function Signature ```python def escape_steps(grid: list[str]) -> int: ``` ### Rules - `grid[r][c]` is `'.'` for an open cell, `'#'` for a wall, `'S'` for the person's starting cell and `'D'` for a cell where a danger source starts. Cells marked `'S'` and `'D'` are open cells. - Everyone moves one cell per minute, only up, down, left or right, never into a wall and never off the grid. The person must move every minute. - Danger sources chase the person as well as they can, so a danger source can occupy an open cell at minute `t` whenever its shortest route to that cell through open cells takes at most `t` moves. With several danger sources, the earliest one counts. Danger sources do not block one another. - The person may stand on a cell at minute `t` only if no danger source can occupy that cell at minute `t` or earlier. Arriving at a cell in the same minute as a danger source counts as being caught. - The person escapes as soon as they stand safely on a border cell, and the answer is that minute. A person who starts on the border escapes at minute `0`. - With no danger sources, the answer is the length of the shortest open route to the border. - Return `-1` when every route is caught or no open route reaches 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 easily in a 32-bit signed integer. ### Examples Positions below are written as (row, column), counting from 0. #### Example 1 ```text Input: grid = ["#####.#", "#S....#", "#.#####", "D.#####", "#.#####"] Output: 5 ``` Going down toward (4, 1) would be shorter, but the danger source starting at (3, 0) can occupy (3, 1) at minute 1, before the person could get there at minute 2. Going right along row 1 and up through the opening at (0, 5) takes 5 moves. The danger source would need 8 minutes to reach (0, 5) and stays behind the person at every cell on that route. #### Example 2 ```text Input: grid = ["##.##", "#...#", "#S#D#", "#####"] Output: -1 ``` The only open border cell is (0, 2), reachable only through (1, 2). The person reaches (1, 2) at minute 2, and the danger source starting at (2, 3) can also be there at minute 2, which counts as being caught. #### Example 3 ```text Input: grid = ["#S#", "#.#", "#D#"] Output: 0 ``` The person starts in the first row, so they are already on the border.

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.

A rectangular grid contains open cells, walls, one person and any number of danger sources. Each minute the person moves to an edge-adjacent open cell, and the danger sources move through open cells at the same speed, chasing the person. The person wants to reach the border of the grid (any cell in the first or last row, or in the first or last column) before the danger sources can catch them. Implement `escape_steps(grid)`, which returns the minimum number of moves the person needs to stand safely on a border cell, or `-1` if no safe route exists. ### Rules - `grid[r][c]` is `'.'` for an open cell, `'#'` for a wall, `'S'` for the person's starting cell and `'D'` for a cell where a danger source starts. Cells marked `'S'` and `'D'` are open cells. - Everyone moves one cell per minute, only up, down, left or right, never into a wall and never off the grid. The person must move every minute. - Danger sources chase the person as well as they can, so a danger source can occupy an open cell at minute `t` whenever its shortest route to that cell through open cells takes at most `t` moves. With several danger sources, the earliest one counts. Danger sources do not block one another. - The person may stand on a cell at minute `t` only if no danger source can occupy that cell at minute `t` or earlier. Arriving at a cell in the same minute as a danger source counts as being caught. - The person escapes as soon as they stand safely on a border cell, and the answer is that minute. A person who starts on the border escapes at minute `0`. - With no danger sources, the answer is the length of the shortest open route to the border. - Return `-1` when every route is caught or no open route reaches the border. `grid` arrives as a list of strings in Python and JavaScript, as `String[]` in Java and as `const std::vector<std::string>&` in C++. The result is an `int` in every language: an answer is always less than `len(grid) * len(grid[0])`, which is at most 250,000, so it fits in a 32-bit signed integer. Positions in the examples are written as (row, column), counting from 0. ### Example 1 ```text Input: grid = ["#####.#", "#S....#", "#.#####", "D.#####", "#.#####"] Output: 5 ``` Going down toward (4, 1) would be shorter, but the danger source starting at (3, 0) can occupy (3, 1) at minute 1, before the person could get there at minute 2. Going right along row 1 and up through the opening at (0, 5) takes 5 moves. The danger source would need 8 minutes to reach (0, 5) and stays behind the person at every cell on that route. ### Example 2 ```text Input: grid = ["##.##", "#...#", "#S#D#", "#####"] Output: -1 ``` The only open border cell is (0, 2), reachable only through (1, 2). The person reaches (1, 2) at minute 2, and the danger source starting at (2, 3) can also be there at minute 2, which counts as being caught.

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

  1. 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.
  2. 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.
  3. A start on the border answers 0 right away, even with a danger source next to it.

Escape to the Border Ahead of the Danger

mediumByteDanceSoftware Engineer

A rectangular grid contains open cells, walls, one person and any number of danger sources. Each minute the person moves to an edge-adjacent open cell, and the danger sources move through open cells at the same speed, chasing the person. The person wants to reach the border of the grid (any cell in the first or last row, or in the first or last column) before the danger sources can catch them.

Implement escape_steps(grid), which returns the minimum number of moves the person needs to stand safely on a border cell, or -1 if no safe route exists.

Rules

  • grid[r][c] is '.' for an open cell, '#' for a wall, 'S' for the person's starting cell and 'D' for a cell where a danger source starts. Cells marked 'S' and 'D' are open cells.
  • Everyone moves one cell per minute, only up, down, left or right, never into a wall and never off the grid. The person must move every minute.
  • Danger sources chase the person as well as they can, so a danger source can occupy an open cell at minute t whenever its shortest route to that cell through open cells takes at most t moves. With several danger sources, the earliest one counts. Danger sources do not block one another.
  • The person may stand on a cell at minute t only if no danger source can occupy that cell at minute t or earlier. Arriving at a cell in the same minute as a danger source counts as being caught.
  • The person escapes as soon as they stand safely on a border cell, and the answer is that minute. A person who starts on the border escapes at minute 0.
  • With no danger sources, the answer is the length of the shortest open route to the border.
  • Return -1 when every route is caught or no open route reaches the border.

grid arrives as a list of strings in Python and JavaScript, as String[] in Java and as const std::vector<std::string>& in C++. The result is an int in every language: an answer is always less than len(grid) * len(grid[0]), which is at most 250,000, so it fits in a 32-bit signed integer.

Positions in the examples are written as (row, column), counting from 0.

Example 1

Input:  grid = ["#####.#",
                "#S....#",
                "#.#####",
                "D.#####",
                "#.#####"]
Output: 5

Going down toward (4, 1) would be shorter, but the danger source starting at (3, 0) can occupy (3, 1) at minute 1, before the person could get there at minute 2. Going right along row 1 and up through the opening at (0, 5) takes 5 moves. The danger source would need 8 minutes to reach (0, 5) and stays behind the person at every cell on that route.

Example 2

Input:  grid = ["##.##",
                "#...#",
                "#S#D#",
                "#####"]
Output: -1

The only open border cell is (0, 2), reachable only through (1, 2). The person reaches (1, 2) at minute 2, and the danger source starting at (2, 3) can also be there at minute 2, which counts as being caught.

Examples

Example 1
Input
(['S'],)
Output
0
Notes
1x1 grid: the start is on the border, so the answer is 0.
Example 2
Input
(['SD'],)
Output
0
Notes
Single row of 2 cells: the start is on the border even with a danger source right next to it.

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.

Comments (0)

No comments yet. Be the first to comment!

Submit your answer

Approved first answer today earns 30 XP
Bold⌘BItalic⌘IInline code⌘`Bullet listTab to nest (○ ■)Numbered listTab to nest (a. i.)QuoteCode block
Formatting help
Signature
def escape_steps(grid: list[str]) -> int:
Sample call
escape_steps(['S'])
Language
Case 1
Input
(['S'],)
Expected
0
Case 2
Input
(['SD'],)
Expected
0

Browse More Questions

Show the approach

Approach

Two breadth-first searches over the grid. First, a multi-source search starts from every 'D' cell at minute 0 and spreads through every non-wall cell, including 'S' and the other 'D' cells, recording for each cell the earliest minute any danger source can occupy it. Cells no source can reach keep a sentinel larger than any possible arrival minute. Second, if 'S' is on the border the answer is 0. Otherwise a search from 'S' enters a neighbor at minute d + 1 only when that neighbor is open, not yet visited and its danger minute is strictly greater than d + 1. The first border cell it enters gives the answer; if the search ends without one, the answer is -1.

Correctness: a cell that is safe at minute t is safe at every earlier minute, because a source that can occupy it by an earlier minute can also occupy it by minute t. So arriving earlier never hurts. By induction on t, if some safe walk stands on cell v at minute t, its previous cell was safely reachable one minute earlier, so the search reaches that cell no later than then and enters v no later than minute t, when v is still safe. The search handles cells in nondecreasing minute order, so the first border cell it accepts has the minimum minute. A 'D' cell has danger minute 0 and is never entered, and the strict comparison turns a same-minute arrival into a catch, as the rules require.

Edge cases: a 1x1 grid, a single row or a single column puts the start on the border, so the answer is 0. A start whose four neighbors are walls or 'D' cells returns -1. With no 'D' cells every danger minute is the sentinel, and the answer is the plain shortest route to the border.

Time complexity:
O(R * C), where R and C are the numbers of rows and columns
Space complexity:
O(R * C)