KatInterview

Robot Grid Exploration with Limited Sensing API

Trees & GraphsModel answer
MediumModel answerTrees & Graphsdfsbacktrackinggraph-traversal

Last 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. Returns true if successful (the cell ahead was open), or false if blocked (robot remains in place).

  • turnLeft() / turnRight() — rotates the robot 90 degrees in place. No return value.

  • isTarget() — returns true if the robot currently occupies the target cell, otherwise false.

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.