Minimum Steps Through an Obstacle Map
Trees & GraphsAuto-graded · 21 test casesLast updated
Tests ability to model a 2D grid as an unweighted graph and apply BFS to find the fewest moves between two corners while avoiding walls.
Minimum Steps Through an Obstacle Map
You have a map represented as an m x n binary grid. Each cell holds either 0 (open ground) or 1 (a wall). You begin at the top-left cell (0, 0) and want to reach the bottom-right cell (m - 1, n - 1).
Each move travels to an adjacent cell in one of the four cardinal directions: up, down, left, or right. You may only enter cells that contain 0.
Write a function min_steps_through_map(grid) that returns the minimum number of moves needed to travel from the start to the destination. If no such route exists, return -1.
Constraints
1 <= m, n <= 200wheremis the number of rows andnis the number of columns.- Every cell is either
0or1. grid[0][0]andgrid[m-1][n-1]are always0.- Diagonal moves are not allowed.
Examples
Example 1
Input: min_steps_through_map([[0, 0, 0], [1, 1, 0], [0, 0, 0]])
Output: 4
Example 2
Input: min_steps_through_map([[0, 1], [1, 0]])
Output: -1
Hints
Hint 1
Think about what search strategy guarantees the fewest moves in a graph where every edge has the same cost. Which classic traversal explores neighbors layer by layer, nearest first?
Hint 2
Keep a separate structure to record which cells have already been discovered. Record a cell's distance from the start the moment you add it to the queue — not when you pull it out — to avoid adding the same cell more than once.
Hint 3
If the queue empties before you reach the bottom-right corner, no open path connects the two corners. What should your function return in that case?
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Why BFS?
Every move costs exactly one step regardless of direction, so the grid is an unweighted graph. In an unweighted graph, Breadth-First Search (BFS) finds the shortest path because it expands cells in rings of increasing distance from the start: all cells one step away, then all cells two steps away, and so on. The first time BFS reaches the destination, the recorded distance is the minimum possible. Depth-first search has no such guarantee without exhaustively exploring every route.
How the Implementation Works
A dist matrix, initialised to -1, plays two roles at once: it marks which cells have been discovered, and it stores each cell's distance from (0, 0). The start cell gets distance 0 and is pushed onto a queue.
On each iteration the front cell is popped. If it is the destination, its distance is the answer. Otherwise, each of the four neighbours is checked: it must be in bounds, be open (0), and not yet discovered (dist == -1). Qualifying neighbours get their distance written immediately and are pushed onto the queue.
Why Mark on Enqueue, Not on Dequeue
Writing the distance when a cell enters the queue, rather than when it leaves, is important for correctness and efficiency. If you waited until the pop, the same cell could be added to the queue multiple times by different neighbours at the same distance. The final answer would still be correct, but the queue could balloon to O(M · N) duplicate entries. Marking on enqueue ensures each cell appears in the queue at most once.
Edge Cases
- 1 × 1 grid (
[[0]]): the start and destination are the same cell. The first cell popped matches the target, so the function returns0. - Destination blocked off: BFS exhausts all reachable open cells without ever reaching
(m-1, n-1)and returns-1. - Winding corridors: BFS does not care about path shape. The queue simply grows longer; the layer-by-layer guarantee still holds.
Complexity
Let M be the number of rows and N the number of columns.
- Time: O(M · N) — each cell is enqueued and dequeued at most once, and each dequeue checks four neighbours.
- Space: O(M · N) — the
distmatrix always uses this much, and the queue holds at most O(M · N) cells.
For the largest allowed grid (200 × 200 = 40,000 cells) this is very fast.
Reference Solution
from collections import deque
from typing import List
def min_steps_through_map(grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
if grid[0][0] == 1 or grid[m - 1][n - 1] == 1:
return -1
# dist[r][c] == -1 means the cell has not been discovered yet.
# It also serves as the visited set, so no separate structure is needed.
dist = [[-1] * n for _ in range(m)]
dist[0][0] = 0
queue = deque([(0, 0)])
directions = ((1, 0), (-1, 0), (0, 1), (0, -1))
while queue:
r, c = queue.popleft()
if r == m - 1 and c == n - 1:
return dist[r][c]
for dr, dc in directions:
nr, nc = r + dr, c + dc
if 0 <= nr < m and 0 <= nc < n:
if grid[nr][nc] == 0 and dist[nr][nc] == -1:
dist[nr][nc] = dist[r][c] + 1 # mark on enqueue
queue.append((nr, nc))
return -1