KatInterview

Maze Exploration with Limited Sensor API

Trees & GraphsModel answer
MediumModel answerTrees & Graphsgraph-traversaldfsstate-tracking

Last updated

Explore an unmapped grid using a restricted movement API to find a target location, tracking state through relative coordinates.

You're implementing control software for a robot navigating an unexplored grid environment. The robot has no map, GPS, or knowledge of the grid's boundaries. You can only interact through this API:

  • move() → bool: attempts to advance one cell in the current facing direction; returns false if the path is obstructed
  • turnLeft(): rotates 90° counterclockwise in place
  • turnRight(): rotates 90° clockwise in place
  • atTarget() → bool: returns true if the robot occupies the goal cell

Write a function that navigates the robot to locate the target cell (if reachable), using only these primitives. Your solution must:

  1. Handle grids of unknown size and shape
  2. Work without global coordinates or absolute compass directions
  3. Avoid infinite loops in grids containing cycles
  4. Return true if the target is found, false if the entire reachable area is explored without finding it

Analyze the correctness of your approach, including how you prevent revisiting cells, and determine the complexity in terms of API calls.

Hints

Hint 1

Depth-first exploration lets you backtrack along the path you came from by reversing your physical movements

Hint 2

Invent your own coordinate system treating the start as origin; track your position and orientation as you move

Hint 3

Mark cells as explored before recursing into them to prevent cycles from causing infinite loops