Mouse, Cheese and Cat
GoogleOnsiteMedium
A mouse wants to travel from its start S to the cheese T on an n by n grid given as a list of strings. The cell symbols are:
S— the mouse's start (exactly one)T— the cheese (exactly one)C— a cat, which never movesW— water, which the mouse cannot enter.— land
The mouse moves one step at a time up, down, left or right. It may revisit cells and may walk through the cat's cell. The safety of a path is the smallest Manhattan distance from any cell on the path, including S and T, to the cat's cell. Distances ignore water: they are computed from coordinates only.
Part 1: Safest path to the cheese
Given the grid, return the largest safety over all paths from S to T. If T cannot be reached, return -1.
- Example 1
- grid
["S...T",".....","..C..",".....","....."]- Output
2
Why: The cat is at (2, 2). The path along the top row keeps every cell at Manhattan distance at least 2 from the cat, and any path must cross column 2, where the farthest possible distance is 2, so no path is safer.
- Example 2
- grid
["S.W.T",".....","..C..",".....","..W.."]- Output
1
Why: Water blocks the top and bottom rows at column 2, so every path crosses column 2 through rows 1 to 3, where the best distance to the cat at (2, 2) is 1.
Constraints
n = len(grid)2 <= n <= 500len(grid[i]) == ngrid[i][j]is one ofS,T,C,W,.- The grid contains exactly one
S, oneTand oneC