Robot Grid Exploration with Limited Sensing API
Trees & GraphsModel answerLast updated
Navigate a robot through an unmapped grid with obstacles using only movement and turn commands to locate a target cell.
You are controlling a robot placed in a grid environment. The grid dimensions are unknown, the robot's starting position is unknown, and the layout of obstacles is unknown. You cannot inspect the grid directly.
The grid contains open cells (passable) and blocked cells (walls). Your robot begins at some open cell, facing in one of the four cardinal directions. Somewhere in the grid is a target cell that the robot must reach.
Available Operations
You control the robot through this interface:
-
move()— attempts to advance the robot one cell forward in its current facing direction. Returnstrueif successful (the cell ahead was open), orfalseif blocked (robot remains in place). -
turnLeft()/turnRight()— rotates the robot 90 degrees in place. No return value. -
isTarget()— returnstrueif the robot currently occupies the target cell, otherwisefalse.
Objective
Write a procedure that explores the grid and locates the target. Once the robot reaches the target, stop immediately. If the target is unreachable from the starting position, your procedure should eventually terminate and report failure.
You may track state internally (such as which cells you have visited), but you cannot access or query the grid structure directly.
Function Signature
Implement:
def find_target(robot) -> bool:
# Returns True if target is found (robot stops on target)
# Returns False if target is unreachable after full exploration
Assume the reachable region of the grid is finite.
Hints
Hint 1
Treat the starting cell as the origin of your own coordinate system and the initial facing direction as a reference heading. All exploration is relative to this frame.
Hint 2
Use depth-first search with physical backtracking: after exploring a neighbor recursively, turn around, step back, and turn around again to restore your position and heading.
Hint 3
Maintain a visited set keyed by relative coordinates. Mark both successfully visited cells and blocked cells as visited to prevent redundant collision checks.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
Understanding the Constraints
The core challenge is that you cannot see the grid. You must build your own map as you go, using only the robot's sensors: successful or failed movement, and the target detector.
Since the starting position and initial orientation are unknown, you define them yourself. Call the start (0, 0) and the initial facing direction "north" (direction index 0). Everything you discover is positioned relative to this frame.
Approach: Depth-First Search with Backtracking
The robot physically moves through the grid, so you must physically return after exploring each branch. This is analogous to classic DFS on a graph, except here the "undo" step is not automatic—you must explicitly turn and move the robot back.
Core Strategy:
-
Coordinate system: Start is
(0, 0). Represent direction as an integer 0–3 mapping to the four cardinal directions in clockwise order: north(-1, 0), east(0, 1), south(1, 0), west(0, -1). -
State tracking: Maintain a
visitedset of(row, col)coordinates. Mark cells when you attempt to visit them, whether the visit succeeds or the cell is blocked. -
Recursive exploration:
- On entering a cell, immediately check
isTarget(). If true, returnTrueup the call stack without backtracking—the robot stays put. - Try moving in all four directions. For each unvisited neighbor, mark it visited and attempt
move(). - If the move succeeds, recurse on the new cell. If recursion returns
False, the target was not found down that branch, so backtrack: turn 180°, move back, turn 180° again. This restores both position and heading. - After trying each direction, turn right once. After four iterations, the robot faces its original heading.
- On entering a cell, immediately check
-
Backtracking correctness: The algorithm maintains an invariant: if
dfs(r, c, d)returnsFalse, the robot ends at(r, c)facing directiond, exactly as it started. This ensures the recursion stack matches the robot's physical state.
Why This Works
- Completeness: DFS explores every cell reachable from the start. If the target is reachable, you will find it.
- Termination: Each cell is visited at most once. On a finite grid, recursion depth is bounded.
- Immediate stopping: When
isTarget()returnsTrue, the function returnsTrueimmediately, bypassing all backtracking logic. The robot stops on the target. - Blocked cells: Marking walls as visited prevents redundant collision attempts.
Complexity
Let R be the number of reachable open cells and W the number of wall cells adjacent to the reachable region.
- Time / API Calls: O(R + W). Each open cell is entered once, requiring 4 direction checks and 4 turns. Each edge is traversed forward and backward. Each wall is tested once per adjacent open cell.
- Space: O(R + W) for the visited set, plus O(R) recursion depth in a worst-case linear path (like a long corridor).
Edge Cases
- Start is target: return
Truebefore any movement. - Start surrounded by walls: four failed moves, return
False. - Target unreachable: after full exploration, return
False. Robot returns to start facing its original direction. - Cycles in the open region: handled by the visited set; no cell is re-entered.
- Deep recursion in large grids: Python's default recursion limit may be insufficient. Increase it, or rewrite using an explicit stack to simulate recursion.
Implementation
from typing import Set, Tuple
# Clockwise directions: north, east, south, west
DIRECTIONS = [(-1, 0), (0, 1), (1, 0), (0, -1)]
def find_target(robot) -> bool:
visited: Set[Tuple[int, int]] = set()
visited.add((0, 0))
def backtrack():
"""Turn around, move back one cell, turn around again."""
robot.turnRight()
robot.turnRight()
robot.move()
robot.turnRight()
robot.turnRight()
def explore(row: int, col: int, facing: int) -> bool:
"""
DFS from (row, col) facing direction `facing`.
Returns True if target found, False otherwise.
Invariant: if False, robot is at (row, col) facing `facing`.
"""
if robot.isTarget():
return True
for i in range(4):
current_dir = (facing + i) % 4
dr, dc = DIRECTIONS[current_dir]
next_row, next_col = row + dr, col + dc
if (next_row, next_col) not in visited:
visited.add((next_row, next_col))
if robot.move(): # successfully moved to next cell
if explore(next_row, next_col, current_dir):
return True # target found, stop immediately
backtrack() # target not found, return to (row, col) facing current_dir
# else: move failed (wall), continue checking other directions
robot.turnRight() # now facing (facing + i + 1) % 4
return False # all four directions explored, no target found
return explore(0, 0, 0)
Common Mistakes
- Forgetting to turn back after backtracking: after turning 180° and moving, you must turn 180° again to restore the original heading.
- Not marking walls as visited: this causes redundant collision checks and wasted API calls.
- Backtracking after finding the target: if
isTarget()is true, return immediately without callingbacktrack(). The robot should stop on the target, not return to the start. - Off-by-one errors in direction indexing: ensure that after four
turnRight()calls, the robot faces its original direction. - Ignoring recursion depth limits: for large grids, Python may exceed the default recursion limit (typically 1000). Use
sys.setrecursionlimit()or convert to an iterative solution with an explicit stack.
Discussion Points
In an interview, you might discuss:
- Why DFS instead of BFS? DFS is simpler to implement with physical backtracking. BFS would require queuing moves and finding a path back to each frontier cell, which is more complex.
- Infinite grids: if the reachable region is unbounded and the target does not exist, DFS may never terminate. You could impose a depth limit or switch to iterative deepening.
- Optimizations: tracking the parent cell during DFS can reduce redundant turns. However, the baseline solution is sufficient for most interviews.