Shortest Route Through a Blocked Matrix
Trees & GraphsAuto-graded · 22 test casesLast updated
Find the minimum number of unit moves from the top-left to the bottom-right cell of a 0/1 matrix, or report that no route exists.
You are given a rectangular matrix grid with m rows and n columns. Each entry is either 0 (walkable) or 1 (a blocked cell you may not enter). You begin standing on the cell (0, 0) and want to reach the cell (m-1, n-1).
On each step you may move to a cell that shares an edge with your current cell (up, down, left, or right). Diagonal moves are not allowed. Every step costs exactly 1.
Return the total number of steps in a shortest possible route from the start to the destination. If the destination cannot be reached, return -1.
Rules and edge cases to respect:
- An empty matrix (
[]) or a matrix whose first row is empty ([[]]) has no valid start cell: return-1. - If the start cell or the destination cell is blocked (
1), no route exists: return-1. - A
1 x 1matrix holding[[0]]has start equal to destination: return0. - A
1 x 1matrix holding[[1]]returns-1. - Step counts measure moves, not cells visited. A route through
pcells usesp - 1steps. - You may not pass through or land on blocked cells.
Constraints
0 <= m <= 5000 <= n <= 500- Each entry of
gridis0or1. - When
mandnare both positive, every row has exactlynentries.
Examples
Example 1
Input: min_grid_steps([[0, 0, 0], [1, 1, 0], [0, 0, 0]])
Output: 4
Example 2
Input: min_grid_steps([[0, 1, 0, 0], [0, 1, 0, 1], [0, 0, 0, 0]])
Output: 5
Example 3
Input: min_grid_steps([[0, 1], [1, 0]])
Output: -1
Hints
Hint 1
Model each walkable cell as a node and each edge-adjacency between walkable cells as a unit-weight edge; then you need shortest distances in an unweighted graph.
Hint 2
A breadth-first traversal visits cells in increasing order of distance, so the first time you reach a cell you already know the minimum number of moves to it.
Hint 3
Record a cell as visited at the moment you enqueue it rather than when you dequeue it, so that no cell is enqueued twice.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Treat the walkable cells as the vertices of a graph, and connect two vertices whenever their cells share an edge and both hold 0. Every edge has weight 1, so a breadth-first search starting from (0, 0) discovers cells in non-decreasing order of distance from the start.
Maintain a second matrix steps of the same shape, initialized to -1 to mean "not yet reached". Set steps[0][0] = 0 and push (0, 0) into a FIFO queue. Repeatedly pop the front cell; if it is the destination, return its recorded value. Otherwise examine its four edge-neighbors: for each one that is inside the matrix, holds 0, and still has -1 in steps, assign it steps[current] + 1 and enqueue it. If the queue drains without ever popping the destination, return -1.
Why this is correct. A cell's recorded value is assigned exactly once, the first time any neighbor reaches it. Suppose some cell v is first labeled from u. If a shorter route to v existed, let w be the cell just before v on that route, so w sits strictly closer to the start than u. Breadth-first order guarantees w is popped before u, and therefore w would have labeled v first — a contradiction. Hence every label equals the true shortest distance, and the label of the destination when popped is the answer. If the destination is never popped, it lies outside the start's connected component, so -1 is right.
Complexity. Each cell is enqueued at most once, and each pop inspects four neighbors: O(m * n) time. The steps matrix and the queue together use O(m * n) space.
from collections import deque
from typing import List
def min_grid_steps(grid: List[List[int]]) -> int:
if not grid or not grid[0]:
return -1
m, n = len(grid), len(grid[0])
if grid[0][0] == 1 or grid[m - 1][n - 1] == 1:
return -1
steps = [[-1] * n for _ in range(m)]
steps[0][0] = 0
queue = deque([(0, 0)])
moves = ((1, 0), (-1, 0), (0, 1), (0, -1))
while queue:
r, c = queue.popleft()
if r == m - 1 and c == n - 1:
return steps[r][c]
for dr, dc in moves:
nr, nc = r + dr, c + dc
if 0 <= nr < m and 0 <= nc < n:
if grid[nr][nc] == 0 and steps[nr][nc] == -1:
steps[nr][nc] = steps[r][c] + 1
queue.append((nr, nc))
return -1