KatInterview

Minimum Moves Across an Obstacle Grid

Trees & GraphsAuto-graded · 18 test cases
HardAuto-gradedTrees & Graphsbfsgraph traversalgrid

Last 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 position
  • destination = [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 origin or destination is a blocked cell (1), no valid path can start or end there, so return -1.
  • If origin and destination are the same cell, return 0 (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 valid i, j
  • origin and destination each contain exactly two integers [row, col]
  • 0 ≤ origin[0], destination[0] < m
  • 0 ≤ 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.