Katkat

Guide a mouse to find cheese with APIs

MetaSoftware Engineer · Technical Screen

Last updated

This problem tests your ability to navigate an unknown environment by maintaining internal state and implementing an efficient search algorithm to reach a target.

Problem Statement

You are tasked with helping a mouse navigate a 2D grid of unknown dimensions to find a piece of cheese. You do not have access to a grid map. Instead, you interact with the environment via an interface:

class GridEnvironment:
    def can_move(self, direction: str) -> bool:
        # direction: 'up', 'down', 'left', 'right'
        # returns True if the move is valid and not hitting a wall

    def move(self, direction: str) -> bool:
        # moves the mouse in the direction
        # returns True if successful, False otherwise

    def is_cheese(self) -> bool:
        # returns True if the mouse is currently on the cheese

Your goal is to implement a function find_cheese(env: GridEnvironment) -> bool that returns True once the mouse reaches the cheese.

Constraints

  • The grid can contain cycles and walls.
  • You must visit every reachable cell or find the cheese.
  • The state space is finite but the boundaries of the grid are unknown.

Example

  • Input: The mouse starts at (0,0). can_move('right') is True, can_move('up') is False.
  • Output: A sequence of moves that terminates when is_cheese() returns True.

Edge Cases

  • The cheese is unreachable (you should return False after exhausting all options).
  • Dead ends or loops in the grid pathing.
  • Starting position is already the cheese.

Hints

Hint 1

Represent the grid as a graph where each node is a coordinate (x, y) and edges are the allowed movements.

Hint 2

Use a set to keep track of visited coordinates to prevent infinite loops during your search.

Hint 3

Implement a Depth-First Search (DFS) or Breadth-First Search (BFS) to systematically explore the unknown space, remembering to backtrack after a move.

Follow-up questions

  • How would you optimize the search if you knew the maximum grid dimensions in advance?
  • What changes are needed if the path cost between cells is not uniform (e.g., some cells are 'muddy' and take longer to traverse)?
  • How would you modify your approach if the grid was dynamic, meaning walls could appear or disappear after each move?