Maze Exploration with Limited Sensor API
Trees & GraphsModel answerLast 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; returnsfalseif the path is obstructedturnLeft(): rotates 90° counterclockwise in placeturnRight(): rotates 90° clockwise in placeatTarget()→bool: returnstrueif 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:
- Handle grids of unknown size and shape
- Work without global coordinates or absolute compass directions
- Avoid infinite loops in grids containing cycles
- Return
trueif the target is found,falseif 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
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Approach
This problem requires depth-first search with physical backtracking, where we build our own coordinate frame since the robot has no global positioning.
Core Strategy:
-
Relative coordinates: Designate the starting cell as
(0, 0)and the initial heading as direction0(we can call this "north," though absolute orientation is arbitrary). Maintain a coordinate system based on this reference frame. -
State tracking: Keep track of
(x, y, facing_dir)manually. EachturnRight()increments direction by 1 (mod 4). Each successfulmove()advances position by the delta vector for the current direction. -
Visited set: Store explored cells to avoid revisiting. Crucially, mark cells as visited before recursing into them—this prevents infinite loops in cyclic environments.
-
Four-direction exploration: At each cell, try moving in all four directions. For each unvisited neighbor that accepts a
move(), recurse into it. After exploring a branch that doesn't find the target, physically backtrack by reversing direction, moving, and reversing again.
Critical Invariant
The correctness hinges on maintaining this property:
When
explore(x, y, dir)returnsfalse, the robot is physically back at(x, y)facingdir.
This holds because:
- The exploration loop performs exactly 4
turnRight()calls (one per direction attempt), completing a full rotation back to the original heading - When recursion into a neighbor fails, we execute a physical reversal: turn 180°, move one cell (guaranteed to succeed since we just came from there), turn 180° again
- Failed
move()attempts don't change the robot's state
Why It Works
Completeness: If the target is reachable, there exists a path from start to target. DFS systematically tries all four directions from each cell. A reachable cell is skipped only if already visited, meaning it was already explored through another path. Therefore, we eventually test atTarget() at every reachable cell.
Soundness: We return true only when atTarget() confirms the robot's current location is the goal. The invariant ensures our coordinate tracking matches physical reality.
Termination: Each reachable cell enters the visited set exactly once and is never removed. With finitely many reachable cells, the search completes. (Note: in an infinite grid without a target, no algorithm can guarantee termination—we assume finite reachable space.)
Complexity
For N reachable cells:
- Movements: Each cell attempts ≤ 4 forward moves. Successful moves form a spanning tree with
N-1edges. Each tree edge is traversed twice (entering and backtracking), givingO(N)successful moves. Failed move attempts are alsoO(N). - Rotations: 4 per cell during exploration, plus 4 per backtrack operation, totaling
O(N). - API calls:
O(N)total across all operations. - Space:
O(N)for the visited set and recursion stack depth (worst case: a long corridor).
Why not BFS? While BFS would also correctly explore the graph, a physical robot cannot teleport between frontier cells. Walking between them would require additional traversals, inflating the cost significantly. DFS keeps movement proportional to the tree structure.
Edge Cases
- Target at start: Checked immediately before any movement
- Isolated start cell: All four moves fail; return
false - Large grid: May need to increase recursion limit or implement iterative DFS with explicit stack
- Cycles: Handled correctly by the visited set
Implementation
import sys
from typing import Set, Tuple
class RobotAPI:
def move(self) -> bool: ...
def turnLeft(self) -> None: ...
def turnRight(self) -> None: ...
def atTarget(self) -> bool: ...
# Clockwise direction vectors: north, east, south, west
DELTA_X = (0, 1, 0, -1)
DELTA_Y = (1, 0, -1, 0)
def locate_target(robot: RobotAPI) -> bool:
sys.setrecursionlimit(10_000)
visited: Set[Tuple[int, int]] = set()
def reverse_step() -> None:
"""Move backward one cell, maintaining current facing direction."""
robot.turnRight()
robot.turnRight()
robot.move()
robot.turnRight()
robot.turnRight()
def explore(x: int, y: int, facing: int) -> bool:
"""
Explore from position (x, y) while facing direction 'facing'.
Returns True if target found, False otherwise.
Guarantees robot returns to (x, y) facing 'facing' if False.
"""
if robot.atTarget():
return True
visited.add((x, y))
# Try all four directions
for i in range(4):
current_dir = (facing + i) % 4
next_x = x + DELTA_X[current_dir]
next_y = y + DELTA_Y[current_dir]
if (next_x, next_y) not in visited:
if robot.move():
# Mark before recursing to prevent cycles
visited.add((next_x, next_y))
if explore(next_x, next_y, current_dir):
return True
# Target not found; backtrack to (x, y)
reverse_step()
robot.turnRight() # Rotate to next direction
# Completed full rotation; facing original direction again
return False
return explore(0, 0, 0)
Common Mistakes
- Marking visited after recursion: Causes infinite loops in cyclic grids
- Forgetting to restore orientation: Breaks the invariant, leading to coordinate system corruption
- Using BFS without considering physical cost: Theoretically correct but impractical for embodied agents
- Not handling the target-at-start case: Misses immediate success
- Assuming absolute directions exist: The robot has no compass; only relative turns matter