Mouse, Cheese and Cat

Asked at GoogleOnsite

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 moves
  • W — 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

  1. Example 1

    Input: grid = ["S...T",".....","..C..",".....","....."]

    Output: 2

    Explanation: 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.

  2. Example 2

    Input: grid = ["S.W.T",".....","..C..",".....","..W.."]

    Output: 1

    Explanation: 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.

Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question

Code

Loading editor…

Ln 1, Col 1

Start an attempt to use Coach.