Mouse, Cheese and Cat
Asked at Google
Reported by the problem's creator, not verified
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.
Examples
Example 1
Input: grid =
["S...T",".....","..C..",".....","....."]Output:
2Explanation: 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
Input: grid =
["S.W.T",".....","..C..",".....","..W.."]Output:
1Explanation: 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.