Mapping a Hidden Maze: Shortest Route for a Sensing Robot
Trees & GraphsModel answerLast 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 directiond. It returnsTrueon success andFalseif 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 returnNone. - 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core idea
Sensing is free and moving is not, so the question becomes: what is the least the robot must learn before it can prove a route is shortest?
Keep a map in which each cell is UNKNOWN, OPEN or BLOCKED, and compute two kinds of distance:
- Optimistic distance. Run BFS treating
UNKNOWNcells as open. The real grid can only have more walls than this model, so this distance is a lower bound on the true shortest distance. - Confirmed distance. Run BFS using only cells known to be open. Any route found really exists, so it is an upper bound.
When the optimistic shortest route consists entirely of confirmed-open cells, the two bounds coincide. That route is shortest and exploration can stop.
Algorithm
- Sense at the start.
- Run optimistic BFS from
(0,0)to the goal. - If there is no route, the goal is unreachable. BFS over confirmed-open cells back to
(0,0), walk it, and returnNone. - If every cell on the route is confirmed open, return its moves.
- Otherwise find the first unknown cell on the route. The cell just before it is open but not yet visited, because every visited cell has had all its neighbours sensed. Walk to that cell over confirmed-open cells, sense, and go back to step 2.
This explores only where a shorter route might still hide, rather than mapping the entire grid first. It is the same free-space-assumption idea used by D* style planners.
Why it is correct
- Lower bound. Any truly open route is also legal in the optimistic graph, so the optimistic distance never exceeds the true one.
- Optimal on return. A returned route uses only confirmed-open cells and has length equal to the lower bound, so nothing shorter can exist.
- Failure is sound. If even the optimistic graph has no route, no real grid consistent with what we have seen can have one. This covers both a blocked goal and a goal sealed off by known walls.
- A frontier cell always exists and is reachable. The prefix of the route before the first unknown cell is entirely open and starts at
(0,0). The robot itself stands on a cell connected to the start through open cells. So an open path from the robot to the frontier exists. - Termination. Each loop iteration visits a new cell, so there are at most
M*Niterations.
Complexity
- Computation. There are at most
M*Niterations, each doing up to three BFS passes ofO(M*N). That isO((M*N)^2)in the worst case, around 10^8 elementary steps at 100 x 100, and much less in practice. An incremental planner such as D* Lite would avoid recomputing from scratch. - Memory.
O(M*N)for the map, the visited set and BFS parents. - Moves. Minimising physical movement while exploring an unknown graph is hard in general, so this is a strong heuristic rather than a guaranteed optimum. In open terrain the robot heads almost straight at the goal. In a maze that forces backtracking, movement can grow to about
O((M*N)^2)in the worst case.
Code
from collections import deque
STEP = {'U': (-1, 0), 'D': (1, 0), 'L': (0, -1), 'R': (0, 1)}
PREF = ['R', 'D', 'L', 'U'] # fixed tie-break order
UNK, OPEN, WALL = 0, 1, 2
def find_path(goal, grid_dims, robot):
rows, cols = grid_dims
gr, gc = goal
if not (0 <= gr < rows and 0 <= gc < cols):
return None
cell = [[UNK] * cols for _ in range(rows)]
cell[0][0] = OPEN
def look():
r, c = robot.get_position()
for d, blocked in robot.sense().items():
dr, dc = STEP[d]
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols:
cell[nr][nc] = WALL if blocked else OPEN
def bfs(src, dst, ok):
parent = {src: None}
q = deque([src])
while q:
cur = q.popleft()
if cur == dst:
break
for d in PREF:
nxt = (cur[0] + STEP[d][0], cur[1] + STEP[d][1])
if (0 <= nxt[0] < rows and 0 <= nxt[1] < cols
and nxt not in parent and ok(nxt)):
parent[nxt] = (cur, d)
q.append(nxt)
if dst not in parent:
return None
cells, moves, cur = [], [], dst
while parent[cur] is not None:
prev, d = parent[cur]
cells.append(cur)
moves.append(d)
cur = prev
return cells[::-1], moves[::-1]
def walk(moves):
for d in moves:
if not robot.move(d):
raise RuntimeError("map disagrees with the world")
optimistic = lambda p: cell[p[0]][p[1]] != WALL
confirmed = lambda p: cell[p[0]][p[1]] == OPEN
look()
while True:
plan = bfs((0, 0), goal, optimistic)
if plan is None:
back = bfs(tuple(robot.get_position()), (0, 0), confirmed)
walk(back[1])
return None
cells, moves = plan
idx = next((i for i, (r, c) in enumerate(cells)
if cell[r][c] == UNK), None)
if idx is None:
return moves
frontier = cells[idx - 1] if idx > 0 else (0, 0)
trip = bfs(tuple(robot.get_position()), frontier, confirmed)
walk(trip[1])
look()
Edge cases
- Goal equals start. The route is empty, so the function returns
[]with no movement. - Goal out of bounds. Return
Noneimmediately. - Goal blocked. A neighbouring sense reveals it, the optimistic BFS fails, and the robot goes home.
- Goal walled in. Failure is detected as soon as the enclosure is known, possibly long before the whole grid is explored.
- Open grid. The first optimistic route is followed with no detours.
Common mistakes
- Mapping everything with DFS first, which wastes moves on cells that cannot matter.
- Treating unknown cells as blocked, which can wrongly report "unreachable".
- Treating unknown cells as open and never verifying them, which can return an invalid route.
- Walking through unknown cells on the way to the frontier instead of staying on confirmed-open ones.
- Forgetting that off-grid neighbours come back as blocked and need a bounds check.