Navigate unknown maze to find target
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Overview: This question evaluates understanding of graph traversal and exploration algorithms, representation of visited state and frontiers, path optimality, and complexity analysis in an environment constrained to local actions.
Constraints
- 1 <= R, C <= 1000 (R = number of rows, C = number of columns).
- Each cell value is one of: 0 (open), 1 (wall), or 2 (cheese).
- There is at most one cheese cell relevant to the answer; if several exist, return the distance to the nearest reachable one.
- 0 <= start[0] < R and 0 <= start[1] < C for valid input, but the function must also return -1 for an out-of-bounds or wall start.
- Movement is restricted to the four orthogonal directions (up, down, left, right).
Examples
Input: ([[0, 0, 0], [1, 1, 0], [0, 0, 2]], (0, 0))
Expected Output: 4
Explanation: The wall row forces a detour: (0,0)->(0,1)->(0,2)->(1,2)->(2,2), which is 4 moves — the shortest path around the obstacle.
Input: ([[0, 1, 2], [0, 1, 0], [0, 0, 0]], (0, 0))
Expected Output: 6
Explanation: A vertical wall splits the grid, so the mouse must go all the way down the left column, across the bottom row, and up the right column to reach the cheese — 6 moves.
Hints
- BFS, not DFS: BFS explores cells in order of increasing distance, so the first time you reach the cheese you have used the fewest possible moves. DFS can find a path but not necessarily the shortest one.
- Mark a cell visited the moment you enqueue it (not when you dequeue it). Otherwise the same cell can be pushed multiple times, inflating the queue and risking redundant exploration.
- Handle the degenerate cases up front: start out of bounds, start on a wall, and start already on the cheese (answer 0). Walls (value 1) must never be entered or enqueued.
- Track distance by storing it alongside each queued cell (or by processing the queue one 'level' at a time). When the frontier empties without finding a 2, the cheese is unreachable — return -1.