Shortest path for a robot on a warehouse grid
Problem
In grid, 0 is a free cell and 1 is blocked. A robot moves up, down, left or right one cell per step. Return the minimum number of moves from start to goal, or −1 if the goal is unreachable or either endpoint is blocked.
Signature
def shortest_path_grid(grid: list[list[int]], start: tuple[int, int], goal: tuple[int, int]) -> int: ...Examples
The visible tests, as an interactive Python session would show them: each call and the value it should give.
>>> shortest_path_grid([[0,0,0],[1,1,0],[0,0,0]], (0,0), (2,0)) == 6
True
>>> shortest_path_grid([[0,1],[1,0]], (0,0), (1,1)) == -1
TrueHints
BFS from start; mark visited at enqueue time (not dequeue).
Bounds checks; start == goal returns 0; unreachable or blocked goal -> -1.
Return the minimum number of moves; shortest path, not DFS.
Reference solution
from collections import deque
def shortest_path_grid(grid, start, goal):
R, C = len(grid), len(grid[0])
if grid[start[0]][start[1]] == 1 or grid[goal[0]][goal[1]] == 1:
return -1
q = deque([(start, 0)]); seen = {tuple(start)}
while q:
(r, c), d = q.popleft()
if (r, c) == tuple(goal):
return d
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < R and 0 <= nc < C and grid[nr][nc] == 0 and (nr, nc) not in seen:
seen.add((nr, nc)); q.append(((nr, nc), d + 1))
return -1What a strong solution covers
- BFS with a visited set marked at enqueue time, O(R·C).
- Bounds checks; start == goal returns 0.
- Follow-ups: A* with a Manhattan heuristic; multi-robot collision avoidance (time-expanded graph).
Common mistakes
- DFS (not shortest)
- marking visited at dequeue time, which causes duplicate enqueues.