Problem · Graph

Mouse and Cheese Reachability

Learn this problem
MediumMeta logoMetaFULLTIMEONSITE INTERVIEW
See Meta hiring insights

Problem statement

A mouse starts at coordinate (0, 0) in a finite rectangular environment. The environment is serialized as grid for this function runner:

  • '.' is an open cell.
  • '#' is a blocked cell.
  • 'C' is the unique open cell containing cheese.

A movement oracle move(x, y) accepts only an orthogonally adjacent absolute coordinate. It returns false and leaves the mouse in place when that coordinate is blocked or outside the grid; otherwise it moves the mouse and returns true. A goal oracle reachCheese() returns whether the current cell contains the cheese.

Return whether some sequence of successful oracle moves can reach the cheese. The serialized grid defines exactly the same movement outcomes, so you may compute the result directly from it.

Function

canReachCheese(grid: String[]) → boolean

Examples

Example 1

grid = ["..#",".#C","..."]return = true

The mouse can move down to row 2, cross to column 2, and then move up to the cheese.

Example 2

grid = [".#C","###","..."]return = false

The blocked cells separate the starting cell from the cheese.

Example 3

grid = ["C"]return = true

The mouse begins on the cheese, so no movement is needed.

Constraints

  • 1 <= grid.length <= 500.
  • 1 <= grid[0].length <= 500.
  • Every row has the same length.
  • Every cell is '.', '#', or 'C'.
  • grid[0][0] is open or contains cheese.
  • Exactly one cell contains 'C'.

More Meta problems

drafts saved locally
public boolean canReachCheese(String[] grid) {
    // Write your code here.
}
grid["..#",".#C","..."]
expectedtrue
checking account