Quick Overview

Given a grid with a rat, a piece of bread, cats and obstacles, find the path from the rat to the bread whose closest approach to any cat is as large as possible, or report that no path exists. It tests grid search, distance precomputation and reasoning about a max-min path objective.

Rat-to-bread grid path that maximizes the minimum distance to any cat

Company: Google

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

You are given a rectangular 2D grid where each cell contains one of these characters: `'R'` (the rat's starting position), `'B'` (the bread's position), `'C'` (a cat), `'O'` (an obstacle) or `'.'` (an empty cell). The rat wants to reach the bread while staying as far away from cats as possible. The rat moves one cell at a time up, down, left or right, and it cannot move through obstacles (`'O'`) or cats (`'C'`). For a path from `'R'` to `'B'`, look at every cell on it and take the Manhattan distance from that cell to its nearest cat; the smallest of these values is the path's safety. Return the maximum safety over all paths from the rat to the bread. If there is no valid path from the rat to the bread, return `-1`. ### Function Signature ```python def max_min_cat_distance(grid: list[list[str]]) -> int: ``` ### Rules - `grid` is a list of `m` rows, each with `n` one-character strings. Cells are written as `(row, column)`, zero-indexed. - The distance between cells `(r1, c1)` and `(r2, c2)` is `|r1 - r2| + |c1 - c2|`, measured straight across the grid. Obstacles do not make it longer. - The rat's cell and the bread's cell are part of the path, so both count toward its safety. - If the grid has no cats and the bread is reachable, return `m + n`. A distance between two cells of the grid is at most `m + n - 2`, so this value cannot be confused with a real answer. ### Constraints - `1 <= m, n <= 100` - Each cell is one of `'R'`, `'B'`, `'C'`, `'O'` or `'.'`. - There is exactly one `'R'` and exactly one `'B'` in the grid. - There can be zero or more cats `'C'` and obstacles `'O'`. ### Examples ```text Input: grid = [["R",".",".",".","B"], [".",".","C",".","."], [".",".",".",".","."], [".","C",".",".","."], [".",".",".",".","."]] Output: 1 ``` The cats are at (1, 2) and (3, 1). Using only cells at distance 2 or more, the rat can reach (0, 1), (1, 0) and (2, 0) and nothing else, so 2 is impossible, while the top row reaches the bread with safety 1 (its closest cell is (0, 2), next to the cat at (1, 2)). ```text Input: grid = [["R","O","B"], ["O","O","."], [".",".","."]] Output: -1 ``` Both neighbors of the rat, (0, 1) and (1, 0), are obstacles, so the rat cannot move and the bread is unreachable. ```text Input: grid = [[".",".","C",".","."], ["R",".",".",".","B"], [".",".",".",".","."]] Output: 2 ``` The straight route along row 1 passes (1, 2), one step from the cat at (0, 2), so its safety is 1. Every path must cross column 2, and the best cell there is (2, 2) at distance 2, which a detour through row 2 uses with every other cell at distance 3 or 4.

Overview: Given a grid with a rat, a piece of bread, cats and obstacles, find the path from the rat to the bread whose closest approach to any cat is as large as possible, or report that no path exists. It tests grid search, distance precomputation and reasoning about a max-min path objective.

A rat wants to reach a piece of bread on a rectangular grid while staying as far from cats as possible. `grid` is a list of `m` rows, each a list of `n` one-character strings. Cells are written as `(row, column)`, zero-indexed, and each cell holds one of: - `'R'`: the rat's starting cell - `'B'`: the bread's cell - `'C'`: a cat - `'O'`: an obstacle - `'.'`: an empty cell The rat moves one cell at a time up, down, left or right and cannot move through obstacles (`'O'`) or cats (`'C'`). The distance between cells `(r1, c1)` and `(r2, c2)` is `|r1 - r2| + |c1 - c2|`, measured straight across the grid; obstacles do not make it longer. For a path from `'R'` to `'B'`, look at every cell on it, including the rat's cell and the bread's cell, and take the distance from that cell to its nearest cat. The smallest of these values is the path's safety. Return the maximum safety over all paths from the rat to the bread. If there is no valid path from the rat to the bread, return `-1`. If the grid has no cats and the bread is reachable, return `m + n`; a distance between two cells of the grid is at most `m + n - 2`, so this value cannot be confused with a real answer. The result always lies between `-1` and `m + n` (at most 200), so a 32-bit integer holds it. ### Example 1 ```text Input: grid = [['.', '.', 'C', '.', '.'], ['R', '.', '.', '.', 'B'], ['.', '.', '.', '.', '.']] Output: 2 ``` The cat is at (0, 2). The straight route along row 1 passes (1, 2), one step from the cat, so its safety is 1. Every path must cross column 2, and the best open cell there is (2, 2) at distance 2. The detour (1, 0), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (1, 4) has distances 3, 4, 3, 2, 3, 4, 3, so the answer is 2. ### Example 2 ```text Input: grid = [['R', 'O', 'B'], ['O', 'O', '.'], ['.', '.', '.']] Output: -1 ``` Both neighbors of the rat, (0, 1) and (1, 0), are obstacles, so the rat cannot move and the bread is unreachable. ### Constraints - `1 <= m, n <= 100`, and every row has the same length `n` - Each cell is one of `'R'`, `'B'`, `'C'`, `'O'` or `'.'`. - There is exactly one `'R'` and exactly one `'B'` in the grid. - There can be zero or more cats `'C'` and obstacles `'O'`.

Constraints

  • 1 <= m, n <= 100, where m is the number of rows and n is the number of columns; every row has length n
  • Each cell is one of 'R', 'B', 'C', 'O' or '.'
  • There is exactly one 'R' and exactly one 'B' in the grid
  • There can be zero or more cats 'C' and obstacles 'O'

Examples

Input: ([['R', 'B']],)

Expected Output: 3

Explanation: Smallest grid (1x2) with no cats and the bread reachable, so the answer is m + n = 3.

Input: ([['B'], ['R']],)

Expected Output: 3

Explanation: Single column (2x1) with no cats; the rat steps up to the bread, so the answer is m + n = 3.

Hints

  1. Every path contains the rat's cell and the bread's cell, so their own distances to the nearest cat limit how large the answer can be.
  2. Distances to cats ignore obstacles, so they depend only on where the cats are. Work them out for every cell before looking at paths.
  3. Fix a required minimum distance d. Which cells can the rat still use, and does a route through them exist?

Safest Grid Path from Rat to Bread

mediumGoogleSoftware Engineer

A rat wants to reach a piece of bread on a rectangular grid while staying as far from cats as possible.

grid is a list of m rows, each a list of n one-character strings. Cells are written as (row, column), zero-indexed, and each cell holds one of:

  • 'R': the rat's starting cell
  • 'B': the bread's cell
  • 'C': a cat
  • 'O': an obstacle
  • '.': an empty cell

The rat moves one cell at a time up, down, left or right and cannot move through obstacles ('O') or cats ('C'). The distance between cells (r1, c1) and (r2, c2) is |r1 - r2| + |c1 - c2|, measured straight across the grid; obstacles do not make it longer. For a path from 'R' to 'B', look at every cell on it, including the rat's cell and the bread's cell, and take the distance from that cell to its nearest cat. The smallest of these values is the path's safety.

Return the maximum safety over all paths from the rat to the bread. If there is no valid path from the rat to the bread, return -1. If the grid has no cats and the bread is reachable, return m + n; a distance between two cells of the grid is at most m + n - 2, so this value cannot be confused with a real answer. The result always lies between -1 and m + n (at most 200), so a 32-bit integer holds it.

Example 1

Input: grid = [['.', '.', 'C', '.', '.'],
               ['R', '.', '.', '.', 'B'],
               ['.', '.', '.', '.', '.']]
Output: 2

The cat is at (0, 2). The straight route along row 1 passes (1, 2), one step from the cat, so its safety is 1. Every path must cross column 2, and the best open cell there is (2, 2) at distance 2. The detour (1, 0), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4), (1, 4) has distances 3, 4, 3, 2, 3, 4, 3, so the answer is 2.

Example 2

Input: grid = [['R', 'O', 'B'],
               ['O', 'O', '.'],
               ['.', '.', '.']]
Output: -1

Both neighbors of the rat, (0, 1) and (1, 0), are obstacles, so the rat cannot move and the bread is unreachable.

Constraints

  • 1 <= m, n <= 100, and every row has the same length n
  • Each cell is one of 'R', 'B', 'C', 'O' or '.'.
  • There is exactly one 'R' and exactly one 'B' in the grid.
  • There can be zero or more cats 'C' and obstacles 'O'.

Examples

Example 1
Input
([['R', 'B']],)
Output
3
Notes
Smallest grid (1x2) with no cats and the bread reachable, so the answer is m + n = 3.
Example 2
Input
([['B'], ['R']],)
Output
3
Notes
Single column (2x1) with no cats; the rat steps up to the bread, so the answer is m + n = 3.

Constraints

  • •1 <= m, n <= 100, where m is the number of rows and n is the number of columns; every row has length n
  • •Each cell is one of 'R', 'B', 'C', 'O' or '.'
  • •There is exactly one 'R' and exactly one 'B' in the grid
  • •There can be zero or more cats 'C' and obstacles 'O'

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 max_min_cat_distance(grid: list[list[str]]) -> int:
Sample call
max_min_cat_distance([['R', 'B']])
Language
Case 1
Input
([['R', 'B']],)
Expected
3
Case 2
Input
([['B'], ['R']],)
Expected
3

Browse More Questions

Show the approach

Approach

First compute, for every cell, the Manhattan distance to the nearest cat with one multi-source breadth-first search that starts from all cats at once and moves through every cell of the grid, obstacles included. On a grid with no blocked cells the number of BFS steps between two cells equals their Manhattan distance, so this gives the exact distance for every cell in O(m * n).

A path has safety at least d exactly when every cell on it is open (neither 'O' nor 'C') and has distance at least d. For a fixed d the question becomes plain reachability from 'R' to 'B' inside the open cells whose distance is at least d, and this property is monotone: if it holds for d, it holds for every smaller d.

Run the reachability check with no distance limit first. If the bread is unreachable, return -1. If the grid has no cats, return m + n. Otherwise every open cell is at distance at least 1, so d = 1 succeeds, and no path can beat min(dist(R), dist(B)) because both endpoints lie on every path. Binary search the largest d in that range for which the check succeeds; that d is the answer.

Edge cases: a rat or bread cell next to a cat caps the answer at 1; cats surrounding the bread give -1 because cats cannot be entered; obstacles never lengthen a distance, so a cat behind a wall still counts; a grid with no cats returns m + n only when the bread is reachable, and -1 otherwise.

Time complexity:
O(m * n * log(m + n))
Space complexity:
O(m * n)