Minimum Moves Across an Obstacle Grid
Trees & GraphsAuto-graded · 18 test casesLast updated
Tests BFS-based shortest-path reasoning on an unweighted 2D grid with blocked cells and 4-directional movement.
Minimum Moves Across an Obstacle Grid
You are given an m × n grid of integers where each cell holds either 0 (passable) or 1 (blocked). A traveler standing on a passable cell may step to any of its four orthogonal neighbors (up, down, left, right) as long as the neighbor is inside the grid and is not blocked. Each such step counts as one move.
You are also given two cell coordinates:
origin = [or_, oc]— the starting positiondestination = [dr, dc]— the position you want to reach
Both coordinates are guaranteed to lie within the grid bounds.
Return the minimum number of moves needed to travel from origin to destination. If no such path exists, return -1.
Notes
- If either
originordestinationis a blocked cell (1), no valid path can start or end there, so return-1. - If
originanddestinationare the same cell, return0(provided the cell is passable — this is guaranteed by the rule above).
Constraints
1 ≤ m, n ≤ 500(grid dimensions)grid[i][j] ∈ {0, 1}for all validi,joriginanddestinationeach contain exactly two integers[row, col]0 ≤ origin[0], destination[0] < m0 ≤ origin[1], destination[1] < n
Examples
Example 1
Input: min_moves_grid([[0, 0, 0], [1, 1, 0], [0, 0, 0]], [0, 0], [2, 2])
Output: 4
Example 2
Input: min_moves_grid([[0, 1], [0, 0]], [0, 0], [0, 1])
Output: -1
Example 3
Input: min_moves_grid([[0, 1], [1, 0]], [0, 0], [1, 1])
Output: -1
Hints
Hint 1
Think about what property of BFS makes it ideal for finding shortest paths in a graph where every edge has the same cost.
Hint 2
Use a distance table (initialized to -1) alongside your queue. When you first write a distance into a cell, that distance is already optimal — so you never need to update it.
Hint 3
Handle the blocked-endpoint case before touching the queue. Also remember that discovering the destination while processing a neighbor is the correct moment to return the answer — dequeuing it works too, but only if your distance table is updated at enqueue time.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Why BFS?
The grid is an unweighted graph: every valid move between adjacent passable cells costs exactly 1. In an unweighted graph, BFS explores nodes in non-decreasing order of their distance from the source. The first time any cell is reached, that distance is already minimal — there is no cheaper route that could arrive later, because BFS exhausts all shorter distances before moving on.
DFS would find a path but not necessarily the shortest one. Dijkstra would also be correct, but the priority-queue overhead is unnecessary when all edges cost the same.
Algorithm
- Guard against blocked endpoints. If
originordestinationholds a1, return-1immediately. - Initialize. Create a
distancestable filled with-1(meaning "not yet visited"). Setdistances[origin] = 0and pushoriginonto a FIFO queue. - BFS loop. Dequeue a cell
(r, c). If it is the destination, returndistances[r][c]. Otherwise, examine its four orthogonal neighbors. For each neighbor that is inside the grid, passable, and not yet visited, recorddistances[neighbor] = distances[r][c] + 1and enqueue it. - No path. If the queue drains without reaching the destination, return
-1.
Marking a cell as visited (writing its distance) at enqueue time is important. It prevents the same cell from being enqueued more than once, which keeps the runtime linear.
Correctness
By induction on distance d:
d = 0:originis enqueued with label0. Correct.- Assume every cell at true distance
dcarries labeld. Any cell at true distanced + 1is adjacent to some cell at distanced, so BFS discovers it while processing that level and assigns labeld + 1.
Because labels cannot be smaller than the true distance (every label corresponds to a real path), the first label assigned to any cell is exactly its shortest distance.
Edge Cases
origin == destination:distances[origin] = 0and it is dequeued first, returning0.- Destination enclosed by walls: the queue empties and
-1is returned. - Single-cell grid (
1 × 1): covered by the same-cell case above.
Complexity
Let m and n be the grid dimensions.
- Time: O(m · n) — each cell is enqueued and dequeued at most once; each dequeue examines 4 neighbors (constant work).
- Space: O(m · n) — for the
distancestable and the queue, which together hold at most all cells.
Full Solution
from collections import deque
from typing import List
def min_moves_grid(grid: List[List[int]], origin: List[int], destination: List[int]) -> int:
rows, cols = len(grid), len(grid[0])
or_, oc = origin
dr, dc = destination
# A blocked endpoint makes any path impossible.
if grid[or_][oc] == 1 or grid[dr][dc] == 1:
return -1
# distances[r][c] stores the shortest known distance from origin, -1 = unvisited.
distances = [[-1] * cols for _ in range(rows)]
distances[or_][oc] = 0
queue = deque([(or_, oc)])
directions = ((1, 0), (-1, 0), (0, 1), (0, -1))
while queue:
r, c = queue.popleft()
# Return as soon as we dequeue the destination.
if (r, c) == (dr, dc):
return distances[r][c]
for delta_r, delta_c in directions:
nr, nc = r + delta_r, c + delta_c
if (0 <= nr < rows
and 0 <= nc < cols
and grid[nr][nc] == 0
and distances[nr][nc] == -1):
distances[nr][nc] = distances[r][c] + 1
queue.append((nr, nc))
return -1