Shortest-Path Robot Navigation on an Unmapped Grid
Medium · Software Engineering Fundamentals · DevOps Engineer · Onsite
Problem Statement
A mobile robot begins at the top-left corner (0, 0) of a rectangular grid with rows rows and cols columns (grid_dims = (rows, cols)). Each grid cell is either walkable or obstructed by a wall, and the layout is initially hidden from the algorithm.
You are given a robot controller exposing three methods:
robot.sense() -> Dict[str, bool]— Inspects the four cardinal neighbors'U'(row - 1),'D'(row + 1),'L'(col - 1), and'R'(col + 1). Each direction maps toTrueif and only if that neighboring coordinate lies within the grid bounds and is walkable. Callingsense()incurs zero physical movement cost.robot.move(direction: str) -> bool— Attempts to advance one cell indirection('U','D','L', or'R'). If the destination cell is in bounds and walkable, the robot moves there and returnsTrue; otherwise the robot stays put and returnsFalse. Everymove()call is physically expensive, so total moves should be kept minimal and wall collisions avoided.robot.get_position() -> Tuple[int, int]— Returns the robot's current(row, col)coordinate at zero movement cost.
Implement find_path(robot, target, grid_dims) to discover enough of the grid to navigate from (0, 0) to target = (target_row, target_col):
- If
targetfalls outside0 <= target_row < rowsor0 <= target_col < cols, immediately raiseValueErrorwithout moving the robot. - If
targetis reachable from(0, 0), leave the robot parked attargetand return a shortest sequence of move strings ('U','D','L','R') leading from(0, 0)totarget. - If no walkable route connects
(0, 0)totarget, drive the robot back to(0, 0)and returnNone.
Examples
Example 1
Hidden grid ('.' = walkable, '#' = wall):
row 0: . # # .
row 1: . . . .
Input:
target = (0, 3), grid_dims = (2, 4)
Output:
['D', 'R', 'R', 'R', 'U']
Explanation: At (0, 0), sense() reveals a wall to the right at (0, 1) and an open cell below at (1, 0). Routing around the blocked top row, the robot steps 'D' to (1, 0), 'R' across (1, 1), (1, 2), and (1, 3) while sensing neighbors at each step, and finally 'U' onto (0, 3). It finishes at (0, 3) in 5 physical moves and returns the 5-step shortest path.
Example 2
Hidden grid:
row 0: . . # .
Input:
target = (0, 3), grid_dims = (1, 4)
Output:
None
Explanation: From (0, 0), sense() shows (0, 1) is walkable. After stepping 'R' onto (0, 1), sense() reveals that (0, 2) is a wall blocking the single-row hallway. Because (0, 3) cannot be reached, the robot steps 'L' back to (0, 0) (2 moves total, 0 failed moves) and returns None.
Constraints
1 <= rows, cols <= 100- Starting coordinate
(0, 0)is always walkable. - Movement is restricted to the four cardinal directions
'U','D','L', and'R'. robot.sense()androbot.get_position()are free;robot.move()is costly and the grid is static throughout onefind_pathcall.
Step-by-step walkthrough
Understand the goal and cost rules
A robot starts at
(0, 0)(top-left corner) of anM x Ngrid whose walls are initially hidden. We need to drive the robot totarget = (target_r, target_c)and return a shortest sequence of moves from(0, 0)totarget. If no valid path exists, we must drive the robot back to(0, 0)and returnNone.col -> 0 1 2 3 row 0 [ S | ? | ? | T ] 'U' = row - 1 'D' = row + 1 row 1 [ ? | ? | ? | ? ] 'L' = col - 1 'R' = col + 1Two rules shape the entire design:
- Physical moves (
robot.move) are expensive, so we want to keep the number of moves small and never waste a move bumping into a wall. - Sensing (
robot.sense), checking coordinates (robot.get_position), and CPU work are free, so we can callsense()after every single step and recompute paths in memory whenever needed.
Let's state our exact interface choices upfront (just as you would clarify with an interviewer):
- Signature:
find_path(robot, target, grid_dims)wheregrid_dims = (rows, cols). robot.sense()returns a dictionary such as{'U': False, 'D': True, 'L': False, 'R': True}, whereTruemeans that neighbor lies inside the grid and is clear.- If
targetlies outside the grid bounds, raiseValueErrorimmediately without moving.
from typing import List, Optional, Tuple def find_path( robot, target: Tuple[int, int], grid_dims: Tuple[int, int] ) -> Optional[List[str]]: ...- Physical moves (
Why mapping the whole grid first wastes moves
A tempting two-stage baseline is:
- Walk through every reachable cell using Depth-First Search (DFS — exploring one branch as far as possible and stepping backward when stuck) to uncover the full map.
- Run Breadth-First Search (BFS — exploring cells layer by layer at distance 1, 2, 3, ... so the first path to reach a goal uses the fewest steps) on that complete map.
OPPOSITE = {"U": "D", "D": "U", "L": "R", "R": "L"} DELTAS = {"R": (0, 1), "D": (1, 0), "L": (0, -1), "U": (-1, 0)} def explore_everything_baseline(robot, cell, visited): """Baseline: visit every reachable cell and backtrack along each edge.""" neighbor_clear = robot.sense() for direction in ["R", "D", "L", "U"]: dr, dc = DELTAS[direction] nxt = (cell[0] + dr, cell[1] + dc) if neighbor_clear[direction] and nxt not in visited: visited.add(nxt) robot.move(direction) explore_everything_baseline(robot, nxt, visited) robot.move(OPPOSITE[direction])This baseline always finds a true shortest path, and visiting
Creachable cells takes2 * (C - 1)exploration moves (every tree edge is crossed once forward and once backward).However, it always pays to map the entire grid, even when the target is right next door! On a
100 x 100open grid (10,000cells) wheretarget = (0, 3)is 3 steps to the right, full DFS spends2 * 9,999 = 19,998exploration moves before taking the 3 moves that actually mattered. And on a100 x 100grid, recursive DFS can hit 10,000 stack frames, crashing Python's default recursion limit of 1,000.Core idea: optimistic planning ("clear until proven blocked")
Instead of exploring everywhere, we maintain an internal
M x Nmap where each cell is'?'(unknown),'.'(confirmed clear), or'#'(confirmed blocked), and we plan optimistically: we run BFS from(0, 0)totargetwhile pretending every'?'cell is clear.Why does pretending
'?'is clear give us both speed and a shortest-path guarantee?- Lower-bound property: Every genuinely clear cell in the real world is either
'.'or'?'on our internal map. That means every real valid path is also allowed on our optimistic map, so the optimistic shortest path is never longer than the true shortest path. - Self-certifying stopping rule: If our optimistic shortest path contains zero
'?'cells (every cell on it is already confirmed'.'), then it is a real walkable path whose length equals that lower bound — so no shorter hidden shortcut can possibly exist anywhere else in the grid! - Unreachability proof: Conversely, if BFS cannot reach
targeteven when every'?'cell is treated as clear, then no real path exists either, sotargetis guaranteed unreachable.
That means the robot only needs to inspect
'?'cells that sit on the current optimistic shortest path, completely ignoring irrelevant rooms and corners.- Lower-bound property: Every genuinely clear cell in the real world is either
Represent the internal map and write one reusable BFS
We store
knownas arows x colslist of strings ('?','.','#'). One general helper_bfs_path(known, source, allowed, goals)handles all three pathfinding needs in our algorithm simply by changingallowedandgoals:- Optimistic plan from
(0, 0)to{target}:allowed = (CLEAR, UNKNOWN). - Driving the robot safely to
{goal}:allowed = (CLEAR,). - Stepping toward the closest place to inspect next:
allowed = (CLEAR,)with multiplegoals.
Checking neighbors in the order
['R', 'D', 'L', 'U']also acts as a clean tie-breaker, so an open2 x 3grid from(0, 0)to(1, 2)naturally produces['R', 'R', 'D'].from typing import Dict, List, Optional, Set, Tuple from collections import deque Cell = Tuple[int, int] UNKNOWN = "?" CLEAR = "." BLOCKED = "#" DIRECTIONS = ["R", "D", "L", "U"] DELTAS = {"R": (0, 1), "D": (1, 0), "L": (0, -1), "U": (-1, 0)} def _neighbor(cell: Cell, direction: str) -> Cell: dr, dc = DELTAS[direction] return (cell[0] + dr, cell[1] + dc) def _inside(known: List[List[str]], cell: Cell) -> bool: rows = len(known) cols = len(known[0]) return 0 <= cell[0] < rows and 0 <= cell[1] < cols def _status(known: List[List[str]], cell: Cell) -> str: return known[cell[0]][cell[1]] def _bfs_path( known: List[List[str]], source: Cell, allowed: Tuple[str, ...], goals: Set[Cell], ) -> Optional[List[Cell]]: parent: Dict[Cell, Optional[Cell]] = {source: None} queue = deque([source]) while queue: cell = queue.popleft() if cell in goals: path: List[Cell] = [] step: Optional[Cell] = cell while step is not None: path.append(step) step = parent[step] path.reverse() return path for direction in DIRECTIONS: nxt = _neighbor(cell, direction) if ( _inside(known, nxt) and nxt not in parent and _status(known, nxt) in allowed ): parent[nxt] = cell queue.append(nxt) return None def _direction_between(from_cell: Cell, to_cell: Cell) -> str: for direction in DIRECTIONS: if _neighbor(from_cell, direction) == to_cell: return direction raise ValueError("cells are not adjacent") def _to_directions(cells: List[Cell]) -> List[str]: moves: List[str] = [] for i in range(1, len(cells)): moves.append(_direction_between(cells[i - 1], cells[i])) return moves- Optimistic plan from
Sense for free and never bump into walls
Because
robot.sense()costs zero moves, we call it at(0, 0)before moving and immediately after every physical move, recording all four neighbors intoknown.Two clean guarantees follow automatically:
- Every in-bounds neighbor of every cell the robot has ever visited is already marked
CLEARorBLOCKED(neverUNKNOWN). - Whenever the robot moves, it only steps onto cells already marked
CLEAR, sorobot.move()never fails and never wastes a physical move bumping into an obstacle.
def _sense_and_record(robot, known: List[List[str]]) -> None: here = robot.get_position() neighbor_clear = robot.sense() for direction in DIRECTIONS: neighbor = _neighbor(here, direction) if _inside(known, neighbor): known[neighbor[0]][neighbor[1]] = ( CLEAR if neighbor_clear[direction] else BLOCKED ) def _step(robot, known: List[List[str]], nxt: Cell) -> None: here = robot.get_position() direction = _direction_between(here, nxt) if not robot.move(direction): raise RuntimeError("a cell that was sensed as clear is blocked") _sense_and_record(robot, known) def _walk_to(robot, known: List[List[str]], goal: Cell) -> None: route = _bfs_path(known, robot.get_position(), (CLEAR,), {goal}) for i in range(1, len(route)): _step(robot, known, route[i])- Every in-bounds neighbor of every cell the robot has ever visited is already marked
Pick the next move using sensing spots
Suppose our optimistic
planstill contains at least one'?'cell. How does the robot uncover one safely?Look along
plan = [c0, c1, c2, ...]for every place where a confirmed'.'cell is immediately followed by an'?'cell. Call that'.'cellc_{i-1}a sensing spot: standing onc_{i-1}and callingsense()immediately reveals whetherc_iis'.'or'#'!optimistic plan: (0,0) ---> (1,0) ---> (1,1) ---> (1,2) ---> (1,3) ---> (0,3) known status: '.' '.' '?' '?' '?' '?' ^ sensing spot! (standing on (1,0) reveals (1,1) for free)Three facts keep this airtight:
- At least one sensing spot exists whenever
planhas any'?'cell:plan[0]is(0, 0)('.'), so the very first'?'cell onplanis preceded by a'.'cell. - The robot is never already standing on a sensing spot, because all neighbors of the robot's current cell have already been sensed. So the route to the nearest sensing spot always has at least one step (
route[1]). - Every
'.'cell is connected to(0, 0)through'.'cells, because a cell only becomes'.'when sensed from an already-visited'.'cell. So_bfs_path(known, here, (CLEAR,), spots)always finds a safe path!
We take one step (
route[1]) toward the nearest sensing spot, sense, and only recomputeplanif one of the cells onplanturned out to be'#'(discovering a'.'cell never invalidates or shortens the optimistic plan).def _sensing_spots(plan: List[Cell], known: List[List[str]]) -> Set[Cell]: spots: Set[Cell] = set() for i in range(1, len(plan)): if _status(known, plan[i]) == UNKNOWN and _status(known, plan[i - 1]) == CLEAR: spots.add(plan[i - 1]) return spots def _has_blocked(plan: List[Cell], known: List[List[str]]) -> bool: for cell in plan: if _status(known, cell) == BLOCKED: return True return False- At least one sensing spot exists whenever
Trace the two examples step by step
Trace 1 —
2 x 4grid[".##.", "...."],target = (0, 3):At
(0, 0),sense()reveals(0, 1) = '#'and(1, 0) = '.'. Routing around(0, 1), the initial optimisticplanis(0,0) -> (1,0) -> (1,1) -> (1,2) -> (1,3) -> (0,3).Robot at Newly sensed statuses First '?' on plan Sensing spot Move taken (0, 0) (0,1)='#', (1,0)='.' (1, 1) (1, 0) 'D' -> (1, 0) (1, 0) (1,1)='.' (1, 2) (1, 1) 'R' -> (1, 1) (1, 1) (1,2)='.', (0,1)='#' (1, 3) (1, 2) 'R' -> (1, 2) (1, 2) (1,3)='.', (0,2)='#' (0, 3) (1, 3) 'R' -> (1, 3) (1, 3) (0,3)='.' none! (spots = {}) certified! 'U' -> (0, 3)Total moves: 5 (the exact shortest distance), returning
['D', 'R', 'R', 'R', 'U'].Trace 2 — Blocked
1 x 4hallway..#.,target = (0, 3):1. Start at (0, 0): sense() marks (0, 1) = '.'. Optimistic plan: [(0,0), (0,1), (0,2), (0,3)], sensing spot = {(0, 1)}. 2. Step 'R' to (0, 1): sense() marks (0, 2) = '#' (wall!). _has_blocked(plan, known) is True -> replan returns None (hallway sealed). 3. Loop ends -> _walk_to(robot, known, (0, 0)) steps 'L' back to (0, 0) and returns None.Total moves: 2 (
'R'to see the wall,'L'to return home), with0failed moves.Complete solution
from typing import Dict, List, Optional, Set, Tuple from collections import deque Cell = Tuple[int, int] # Map symbols stored in `known[row][col]`: # '?' = never sensed yet, '.' = confirmed walkable, '#' = confirmed wall. UNKNOWN = "?" CLEAR = "." BLOCKED = "#" # Row grows downward ('D' = row + 1) and column grows rightward ('R' = col + 1). # Keeping 'R' and 'D' first also breaks shortest-path ties cleanly, so an open # 2 x 3 grid from (0, 0) to (1, 2) returns ['R', 'R', 'D']. DIRECTIONS = ["R", "D", "L", "U"] DELTAS = {"R": (0, 1), "D": (1, 0), "L": (0, -1), "U": (-1, 0)} def _neighbor(cell: Cell, direction: str) -> Cell: """Return the adjacent (row, col) coordinate one step in `direction`.""" dr, dc = DELTAS[direction] return (cell[0] + dr, cell[1] + dc) def _inside(known: List[List[str]], cell: Cell) -> bool: """True when `cell` lies within the M x N grid bounds.""" rows = len(known) cols = len(known[0]) return 0 <= cell[0] < rows and 0 <= cell[1] < cols def _status(known: List[List[str]], cell: Cell) -> str: """Read the current map symbol ('?', '.', or '#') at `cell`.""" return known[cell[0]][cell[1]] def _bfs_path( known: List[List[str]], source: Cell, allowed: Tuple[str, ...], goals: Set[Cell], ) -> Optional[List[Cell]]: """Shortest list of cells from `source` to the nearest cell in `goals`. Only steps onto cells whose map symbol is in `allowed`. Returns None if every cell in `goals` is unreachable under `allowed`. """ # parent: {visited_cell: previous_cell_on_shortest_path} (None for `source`). # Doubles as the visited set and the backpointer trail for path reconstruction. parent: Dict[Cell, Optional[Cell]] = {source: None} # queue: FIFO queue of cells ordered by fewest steps from `source`. queue = deque([source]) while queue: cell = queue.popleft() if cell in goals: # Follow parent pointers backward from the reached goal to `source`, # then reverse so the path reads [source, ..., cell]. path: List[Cell] = [] step: Optional[Cell] = cell while step is not None: path.append(step) step = parent[step] path.reverse() return path for direction in DIRECTIONS: nxt = _neighbor(cell, direction) if ( _inside(known, nxt) and nxt not in parent and _status(known, nxt) in allowed ): parent[nxt] = cell queue.append(nxt) return None def _direction_between(from_cell: Cell, to_cell: Cell) -> str: """Find the single-step direction ('R', 'D', 'L', or 'U') between neighbors.""" for direction in DIRECTIONS: if _neighbor(from_cell, direction) == to_cell: return direction raise ValueError("cells are not adjacent") def _to_directions(cells: List[Cell]) -> List[str]: """Convert a list of adjacent cells [c0, c1, ...] into move strings ['R', ...].""" moves: List[str] = [] for i in range(1, len(cells)): moves.append(_direction_between(cells[i - 1], cells[i])) return moves def _sense_and_record(robot, known: List[List[str]]) -> None: """Record all four neighbors of the robot's current cell because sense() is free.""" here = robot.get_position() neighbor_clear = robot.sense() for direction in DIRECTIONS: neighbor = _neighbor(here, direction) # Out-of-bounds neighbors report False in sense(), so guard with _inside # before indexing into the M x N `known` grid. if _inside(known, neighbor): known[neighbor[0]][neighbor[1]] = ( CLEAR if neighbor_clear[direction] else BLOCKED ) def _step(robot, known: List[List[str]], nxt: Cell) -> None: """Move one step onto an adjacent known-clear cell and immediately sense.""" here = robot.get_position() direction = _direction_between(here, nxt) # Because we only ever step onto cells already marked CLEAR, move() must # succeed on any static grid; failing means the environment broke its contract. if not robot.move(direction): raise RuntimeError("a cell that was sensed as clear is blocked") _sense_and_record(robot, known) def _walk_to(robot, known: List[List[str]], goal: Cell) -> None: """Drive the robot to `goal` along a shortest path of already-CLEAR cells.""" route = _bfs_path(known, robot.get_position(), (CLEAR,), {goal}) # Start at index 1 because route[0] is the robot's current position. for i in range(1, len(route)): _step(robot, known, route[i]) def _sensing_spots(plan: List[Cell], known: List[List[str]]) -> Set[Cell]: """Return CLEAR cells on `plan` whose immediate next cell on `plan` is UNKNOWN. Standing on any of these spots and calling sense() reveals that UNKNOWN cell without risking a wasted move into a wall. """ spots: Set[Cell] = set() for i in range(1, len(plan)): if _status(known, plan[i]) == UNKNOWN and _status(known, plan[i - 1]) == CLEAR: spots.add(plan[i - 1]) return spots def _has_blocked(plan: List[Cell], known: List[List[str]]) -> bool: """True if any cell along the current optimistic `plan` was revealed to be BLOCKED.""" for cell in plan: if _status(known, cell) == BLOCKED: return True return False def find_path( robot, target: Tuple[int, int], grid_dims: Tuple[int, int] ) -> Optional[List[str]]: """Return a shortest move list from (0, 0) to target, or None if unreachable. Leaves the robot on `target` when reachable, or back at `(0, 0)` when unreachable. """ rows, cols = grid_dims if not (0 <= target[0] < rows and 0 <= target[1] < cols): raise ValueError("target is outside the grid") target = (target[0], target[1]) # Phase 1: Initialize the internal M x N map as UNKNOWN, mark the starting # cell CLEAR, and sense its four immediate neighbors for free. known = [[UNKNOWN] * cols for _ in range(rows)] start = robot.get_position() known[start[0]][start[1]] = CLEAR _sense_and_record(robot, known) # Phase 2: Build an optimistic shortest plan from `start` to `target` by # treating UNKNOWN cells as walkable. No real path can be shorter than this. plan = _bfs_path(known, start, (CLEAR, UNKNOWN), {target}) # Phase 3: Repeatedly inspect unknown cells along the optimistic plan. while plan is not None: spots = _sensing_spots(plan, known) if not spots: # Zero unknown (and zero blocked) cells remain on `plan`, so `plan` # is a verified real shortest path. Drive the robot to `target`. _walk_to(robot, known, target) return _to_directions(plan) # Take a single safe step through CLEAR cells toward the nearest sensing # spot; the robot is never already on a spot because visited cells have # already sensed all of their neighbors. route = _bfs_path(known, robot.get_position(), (CLEAR,), spots) _step(robot, known, route[1]) # Discovering a CLEAR cell never makes an optimistic path shorter, so we # only need to recompute `plan` if one of its cells turned out BLOCKED. if _has_blocked(plan, known): plan = _bfs_path(known, start, (CLEAR, UNKNOWN), {target}) # Phase 4: Even when treating every UNKNOWN cell as walkable, no path exists, # so `target` is genuinely unreachable. Return the robot to `start`. _walk_to(robot, known, start) return None✅ Submit now — all tests should pass.
Intuition & how it works
Imagine navigating a foggy city grid where looking one block ahead in all four directions is completely free (sense()), while physically driving a block burns expensive fuel (move()). Instead of driving down every street in town just to draw a full map first, you apply optimistic planning: you sketch the shortest route from (0, 0) to target assuming every uninspected foggy block is open, drive up to inspect the unknown blocks along that route, and only redraw the route when you spot a roadblock.
A naive two-phase strategy — mapping every reachable cell with Depth-First Search (DFS) (a traversal that follows one corridor to its end before backtracking) and then finding the shortest path — wastes up to 2 * (M * N - 1) moves exploring the entire grid even if the target is three steps away. Conversely, planning only through already-confirmed clear cells and stopping as soon as one path connects (0, 0) to target can miss an uninspected shortcut and return a path that is longer than optimal. Treating unknown cells as clear solves both problems: the optimistic Breadth-First Search (BFS) (a layer-by-layer search that visits cells in order of step count, guaranteeing a shortest path) produces a lower bound (a value guaranteed to be less than or equal to the true shortest distance), so the moment every cell on that optimistic route is confirmed clear, it is proven to be a true shortest path.
Walk through Example 1 on the 2 x 4 grid [".##.", "...."] from (0, 0) to target = (0, 3):
- At
(0, 0),sense()reveals(0, 1) = '#'(wall) and(1, 0) = '.'(walkable). Because(0, 1)is already known blocked, the optimistic BFS immediately routes around it:(0,0) -> (1,0) -> (1,1) -> (1,2) -> (1,3) -> (0,3). - The first unknown cell on that plan is
(1, 1), right after confirmed-walkable(1, 0). The robot steps'D'onto(1, 0)and senses(1, 1) = '.'. - Next unknowns are
(1, 2)and(1, 3), so the robot steps'R'onto(1, 1)and'R'onto(1, 2), confirming both walkable (and sensing(0, 2) = '#'). - Stepping
'R'onto(1, 3)senses(0, 3) = '.'. Every cell on the plan is now confirmed walkable, so the robot steps'U'onto(0, 3)and returns['D', 'R', 'R', 'R', 'U']in 5 moves with zero wasted steps.
Complexity
- Robot moves (best case): equal to the true shortest distance. When no cell on the initial optimistic path turns out blocked (such as on an open grid), the nearest sensing spot is always the very next cell along the path, so the robot walks straight to
targetin the Manhattan distance (the grid distance|r1 - r2| + |c1 - c2|when moving only horizontally and vertically). - Robot moves (worst case):
O((M * N)^2). Whenever the map learns nothing new on a step, the robot moves one step closer through confirmed-clear cells to the nearest sensing spot, which takes fewer thanM * Nmoves before reaching that spot and uncovering at least one unknown cell; since there areM * Ncells in total and statuses never revert to unknown, the map can learn new cells at mostM * Ntimes. Note that no online algorithm (an algorithm that must make decisions step-by-step with incomplete information) is optimal on every possible map: at a symmetric fork, an adversary can always hide the wall down whichever corridor the robot checks first. - CPU time:
O((moves + 1) * M * N)(O((M * N)^3)in the worst case). Before moving we run one optimistic BFS over at mostM * Ncells, and on each physical move we run one BFS over confirmed-clear cells (O(M * N)work across at most4 * M * Ngrid edges), plus one optimistic replan (O(M * N)) whenever a planned cell turns out blocked (which happens at mostM * Ntimes). - Space:
O(M * N). We store theM x Nknowngrid, plus the BFSparentdictionary,queue, andplanlist, each holding at mostM * Ncell coordinates.
Edge cases
- Target equals
(0, 0): The initial optimistic plan is[(0, 0)], which already has zero unknown cells, sofind_pathreturns[]with0moves. 1 x 1grid: Handled identically;(0, 0)is the only in-bounds coordinate and returns[]with0moves.- Target cell itself is blocked: The robot walks up to a neighbor of
target, senses thattargetis'#', sees that replanning returnsNone, and walks cleanly back to(0, 0). - Target is clear inside a sealed room: Optimistic plans try every way around the walls until every boundary cell of the room is sensed as
'#', after which_bfs_pathreturnsNoneand the robot returns to(0, 0). - Large open grid with nearby target: On a
100 x 100open grid withtarget = (0, 3), the robot takes3moves instead of exploring all10,000cells. - Target outside grid bounds: Checked before touching the robot, raising
ValueErrorimmediately.
Common mistakes
- Returning the robot's physical exploration trail instead of a shortest path. If the robot hit a dead end and detoured, its physical trajectory includes backtracks; always return the clean BFS path from
(0, 0)totarget. - Stopping as soon as known-clear cells connect
(0, 0)totarget. A known-clear detour of length 12 is not proven shortest while an uninspected corridor of length 6 still contains'?'cells. - Declaring
targetunreachable when known-clear cells cannot reach it. Unreachability is proven only when even the optimistic map ('.'+'?') has no path. - Stepping directly onto
'?'cells. Becausesense()is free, always sense from an adjacent'.'cell first; stepping blind wastes expensivemove()calls bumping into walls. - Using recursive DFS on grids up to
100 x 100. A winding snake path has10,000cells, exceeding Python's default recursion limit of1,000. - Forgetting the final robot position contract. The robot must finish on
targetwhen reachable, and back at(0, 0)when unreachable.
Alternative approaches
- Full DFS exploration followed by BFS: Visits every reachable cell in
2 * (C - 1)moves and then runs one BFS. Worse for a single query on an open map, worthwhile only if you plan to answer dozens of future path queries on the exact same static grid. - Agent-centered optimistic navigation (the core idea of D Lite):* Plan optimistically from the robot's current cell to
targetinstead of from(0, 0). This reachestargetvery quickly, though if the problem also requires returning a certified global shortest path from(0, 0), you still need to check that no uninspected route from(0, 0)is shorter. - A* search instead of BFS for in-memory planning: A* search (a shortest-path search guided by a heuristic distance estimate such as Manhattan distance) expands fewer grid cells in CPU memory than BFS, saving CPU work without changing the robot's physical move count.
Follow-up questions
- How would you adapt the planner if the robot runs on a finite battery and must periodically recharge at a base station? Maintain a safety invariant (a condition guaranteed to hold before and after every step): before taking any step to
nxt, verify via BFS overCLEARcells thatremaining_battery - 1is at least the shortest known-clear distance fromnxtback to the base station. Whenever the next step would violate that reserve, drive back alongCLEARcells to recharge and then resume heading toward the nearest sensing spot. Notice that with battery capacityBand the charger at(0, 0), no round trip can visit cells farther thanB // 2steps away, so cells beyond that radius can only be crossed on a final one-way trip totarget. - What changes if walls can shift or appear while the robot is moving? Previously sensed cells can go stale, so record a
last_sensed_steptimestamp per cell and revert old entries back to'?'(or re-sense before each move). In_step,robot.move(direction)can now legitimately returnFalseif an obstacle just appeared; instead of raisingRuntimeError, mark that neighbor'#'and trigger an immediate replan from the robot's current position. For large grids where replans happen constantly, incremental search algorithms like D* Lite update only the affected part of the search tree instead of running BFS from scratch. - How do you balance mapping unknown regions thoroughly against heading straight toward the goal? Full exploration pays a high upfront move cost to guarantee complete knowledge, whereas heading straight toward
targetminimizes moves on easy maps at the risk of dead ends and uncertified shortcuts. Optimistic planning hits the sweet spot for single-query shortest pathfinding because it explores only unknown cells that could plausibly belong to a shorter path than the best confirmed route so far. If you only care about reachingtargetreasonably fast rather than proving global optimality, you can stop exploring as soon as the robot lands ontargetor allow a slack factor1 + epsilonabove the optimistic lower bound.
Follow-up questions
- How would you adapt the planner if the robot runs on a finite battery and must periodically recharge at a base station?
- What changes if walls can shift or appear while the robot is moving?
- How do you balance mapping unknown regions thoroughly against heading straight toward the goal?
Similar questions
- Room Booking Scheduler with Earliest Slot Search
- Fair O(1) Ticket Drum with Duplicate Entries
- Project Architecture Walkthrough and Subsystem Deep Dive
- Architectural Walkthrough of a Shipped Feature
- Collection Mapping Utility and DOM List Renderer
- Immutable N-ary Tree Merge and Codec
More LinkedIn interview questions
- Key-Aligned Merge of Two Rooted N-ary Trees Easy
- Longest Root-to-Leaf Depth from Child Pairs Medium
- Runner-Up Score in a Knockout Min-Tree Medium Pro
- Repeated Word Proximity Queries Hard Pro
- Zigzag Depth-Order Tree Traversal Medium Pro
- Non-Adjacent Flowerbed Placement Medium Pro
- Queue Pooling, Skewed Graphs, and Shrinkage Medium Pro
- Distributed Key-Value Store for Small-Team Internal Services Medium Pro
- Two-Project Architecture and Trade-Off Walkthrough Medium Pro
- Defending a Hard Architectural Trade-Off and Its Implementation Medium Pro