Robot Navigation on a Hidden Grid with DFS and Backtracking
Trees & GraphsModel answerLast updated
Guide a robot through a map it can only discover step by step, reaching the target with no repeated visits, real backtracking, and a clear result when the target is unreachable.
Problem
A vehicle is dropped into a map it has never seen. At each cell it can ask which compass directions are currently open, and it can drive one cell in any open direction. It cannot look ahead, and it has no global view of the map. Your job is to write the search routine that steers the vehicle to the goal without ever wandering in loops.
The setup was described informally, so part of the exercise is fixing the model and stating your assumptions out loud. Use this control interface (names are illustrative):
class Car:
def open_directions(self) -> list[str]:
"""Directions ("N", "E", "S", "W") the car can drive from its current cell."""
def move(self, direction: str) -> None:
"""Drive one cell in an open direction."""
def at_destination(self) -> bool:
"""True when the current cell is the destination."""
Implement:
def find_destination(car) -> list[str] | None
The function must drive the car until it stands on the destination and return the list of directions that forms a route from the starting cell to the destination. If every reachable cell has been explored and the destination was never found, return None.
What is expected
- State your model: grid cells, four directions, and what the car can and cannot sense.
- Explain how you recognize a cell you have already been to, given that the car reports no coordinates.
- Make sure the physical car, not just your data structures, is in the right place at every step of the search.
- Argue that the algorithm terminates and analyze its cost in moves and memory.
- Be ready to discuss whether the route must be shortest, and what changes if it must be.
Points worth clarifying
- Is the map a grid, or a general network of junctions?
- Does the car know its coordinates, or only the moves it has made?
- Are all connections two-way (if A leads to B, does B lead back to A)?
- Is any valid route acceptable, or the shortest one?
- Is the total number of moves, including backtracking, something to minimize?
Hints
Hint 1
The car reports no coordinates, so build your own: start at (0, 0) and update a running position after every move. Use that position as the key in a visited set.
Hint 2
Depth-first search fits well because the car physically stands at one place. After exploring a neighbor, the car must drive back, so for each direction you need its opposite (N and S, E and W).
Hint 3
Keep the current route as a path of moves. Push a direction before recursing, and pop it when you backtrack. Return the path as soon as at_destination() is true, and return None if the whole search finishes without success.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model and assumptions
- The map is a grid. Moves are N, E, S, W, which shift a coordinate by (0, -1), (1, 0), (0, 1), (-1, 0). Any consistent sign convention works.
- The car has no coordinates, so I define a virtual origin at the start cell and track the position by applying each move I make. Two visits to the same cell always produce the same virtual coordinates, so that key is reliable.
- I assume connections are two-way: if I can go from A to B, I can go back from B to A. Without that, physical backtracking is not guaranteed and the problem changes (see the follow-ups).
- Any valid route is acceptable unless the interviewer asks for the shortest.
Approach: DFS with a visited set and physical backtracking
Plain graph DFS assumes you can "jump" to any node. A car cannot, so the search state and the real position must stay in sync. The invariant is:
When a recursive call begins, the car stands on the cell that call represents. When it returns, the car stands on that same cell again.
For each open direction from the current cell:
- Compute the neighbor's virtual coordinate. If it is already in
visited, skip it. This is what prevents driving in circles. - Drive there with
move(d)and appenddto the path. - Recurse. If the recursion reports success, return immediately (the car stays on the destination).
- Otherwise, drive back with
move(opposite[d])and popdfrom the path.
Mark a cell visited when you first arrive, before exploring its neighbors, so that a cycle cannot bring you back into it.
Code
import sys
DELTA = {"N": (0, -1), "E": (1, 0), "S": (0, 1), "W": (-1, 0)}
OPPOSITE = {"N": "S", "S": "N", "E": "W", "W": "E"}
def find_destination(car):
visited = {(0, 0)}
path = []
def dfs(x, y):
if car.at_destination():
return True
for d in car.open_directions():
dx, dy = DELTA[d]
nxt = (x + dx, y + dy)
if nxt in visited:
continue
visited.add(nxt)
car.move(d)
path.append(d)
if dfs(*nxt):
return True
car.move(OPPOSITE[d]) # physical backtrack
path.pop()
return False
return path if dfs(0, 0) else None
Note that car.open_directions() is called once per cell, and the list is read before any moves happen in that frame, so the loop is safe.
For very large maps, Python's recursion limit becomes a risk. Either raise it or convert to an explicit stack of (position, iterator over directions) frames. The logic is identical: on exhausting a frame's directions, pop it and drive back using the opposite of the move that entered it.
Why it terminates and returns the right answer
- Each cell is entered at most once from the search's perspective, because it is marked visited upon the first arrival. The number of recursive calls is therefore at most the number of reachable cells, V.
- If the destination is reachable, DFS eventually reaches it, since it explores all cells reachable from the start before giving up.
- If it is not reachable, every reachable cell is explored, the recursion unwinds to the start, and the function returns
None.
Complexity
- Moves: each edge between two reachable cells is considered from both ends, but is driven along at most twice in each direction (once to go, once to come back) when it leads to an unvisited cell. Total moves are O(V), bounded by roughly 2V. Edges leading to visited cells cost nothing physically, because we skip them without driving.
- Time (computation): O(V + E) with E at most 4V on a grid.
- Memory: O(V) for the visited set, plus O(depth) for the path and recursion stack, which in the worst case (a long corridor) is also O(V).
Trade-offs: DFS versus BFS
- BFS finds a shortest route in terms of moves, but it needs the car to be at the frontier cell. Since the car is a single physical agent, BFS would require driving back to the start or to a shared ancestor for each expansion, which can cost O(V * diameter) moves. That is far worse in physical cost.
- DFS keeps the car moving locally and backtracks only one step at a time, so total movement is linear. The price is that the returned route is not necessarily shortest and can be long and winding.
- If the shortest route is required: first explore the whole reachable map with DFS (O(V) moves), recording coordinates and edges in a map you build. Then run a standard BFS on that known graph offline to get the shortest path. If the car must also end on the destination, drive along that route from the current position (or from the start after backtracking home).
Common mistakes
- Forgetting to backtrack physically. The data structures say you are at cell A, but the car is still at B, so every later coordinate is wrong.
- Marking visited too late (when leaving rather than entering a cell), which can cause infinite loops on cycles.
- Using the move count as the key instead of the position, so revisits are never detected.
- Returning the path including backtracking moves. The returned route must only contain the moves along the successful branch, which is why we pop on backtrack.
- Returning an empty list vs
Noneambiguity. If the start is the destination, return[]. ReturnNoneonly when exploration fails. - Hitting the recursion limit on long corridors.
Follow-ups to be ready for
- One-way streets: the car cannot always return, so backtracking may be impossible. The problem becomes much harder, and without extra knowledge it may be unsolvable in general. State that explicitly.
- Unknown destination location with a cost per move: consider iterative deepening or an A*-style variant if some heuristic is available.
- Non-grid networks: the same algorithm works, but you need some way to identify junctions (for example, a returned ID) or you must infer them from consistent movement.
- Moving obstacles or noisy sensing: the visited map becomes unreliable and needs re-validation.