KatInterview

Mapping a Hidden Maze: Shortest Route for a Sensing Robot

Trees & GraphsModel answer
MediumModel answerTrees & Graphsbfsgridonline-exploration

Last updated

A robot in an unseen grid senses neighbours for free and pays per move. Find a shortest route to a target, or return to the start and report failure if none exists.

Navigating a Hidden Grid

A robot sits at cell (0, 0) of a rectangular grid with M rows and N columns. It must find a shortest route to a goal cell (goal_r, goal_c). Each cell is either open or blocked, but the robot has no map at the start.

The robot exposes three operations:

  • sense() reports whether each of the four neighbouring cells (U, D, L, R) is blocked. Off-grid neighbours count as blocked. This call is free.
  • move(d) tries to step one cell in direction d. It returns True on success and False if the cell is blocked. Every call has a cost.
  • get_position() returns the robot's current (r, c).

U means row − 1, D means row + 1, L means column − 1, and R means column + 1.

Your task

Write find_path(goal, grid_dims, robot) that returns a shortest route from (0, 0) to the goal as a list of direction letters such as ['R', 'R', 'D', 'D'].

  • Build and keep your own picture of the grid as you learn it.
  • Keep physical movement low, since sensing costs nothing.
  • If the goal cannot be reached, drive the robot back to (0, 0) and return None.
  • The robot does not need to walk the final route. It only has to return it.

Limits

  • 1 <= M, N <= 100
  • Movement is only to the four orthogonal neighbours.

Example

On a fully open 3 x 3 grid with goal (2, 2), any route with two R and two D moves is correct, for example ['R', 'R', 'D', 'D']. Fix a tie-break order so your output is deterministic.

Cases to handle

  • The goal is blocked.
  • The goal is walled in and cannot be reached.
  • The grid has no obstacles.
  • The goal is the start cell, or lies outside the grid.

What to cover in your answer

Explain your approach and why the returned route is truly shortest. Give the time and space cost, discuss how many moves the robot makes, and include code.

Hints

Hint 1

Track every cell as unknown, open or blocked. Sensing is free, so sense every time the robot arrives at a new cell.

Hint 2

Run BFS from the start to the goal while pretending unknown cells are open. Think about what that distance guarantees about the real shortest distance.

Hint 3

If the optimistic route contains only cells you have confirmed open, it is a real route and cannot be beaten. If it contains an unknown cell, walk to the last confirmed cell before it, sense there, and recompute.

Hint 4

If the optimistic BFS finds no route at all, then the goal is provably unreachable. Walk home using only confirmed-open cells.