---
title: Shortest path for a robot on a warehouse grid
url: https://gurkanozkan.ai/learn/coding/mle-shortest-path-for-a-robot-on-a-warehouse-grid-35/
markdown: https://gurkanozkan.ai/learn/coding/mle-shortest-path-for-a-robot-on-a-warehouse-grid-35.md
kind: coding
difficulty: Easy
topics:
  - BFS
  - Graphs
  - Grid
json: https://gurkanozkan.ai/api/learn/coding/mle-shortest-path-for-a-robot-on-a-warehouse-grid-35.json
robots: noindex
---

# Shortest path for a robot on a warehouse grid

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

```python
def shortest_path_grid(grid: list[list[int]], start: tuple[int, int], goal: tuple[int, int]) -> int: ...
```

## Examples

Each call and the value it should give.

```python
>>> 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
True
```

## Hints

1. BFS from start; mark visited at enqueue time (not dequeue).
2. Bounds checks; start == goal returns 0; unreachable or blocked goal -> -1.
3. Return the minimum number of moves; shortest path, not DFS.

## Reference solution

```python
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 -1
```

## What 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.
---

*Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.*
