Fewest Moves Through a Walled Maze
Trees & GraphsAuto-graded · 19 test casesLast updated
Compute the minimum number of 4-directional moves between two open cells of a binary maze, or -1 if unreachable; tests breadth-first search on an implicit grid graph.
Fewest Moves Through a Walled Maze
A maze is given as a rectangular grid of integers. A cell containing 0 is open floor, and a cell containing 1 is a wall.
You begin on one open cell and want to reach another open cell. In a single move you may step onto any of the four orthogonally adjacent cells (up, down, left, right). You may never leave the grid, and you may never step onto a wall.
Return the minimum number of moves needed to get from the starting cell to the target cell. If the target cannot be reached, return -1.
Function inputs
grid: a list ofmrows, each a list ofnintegers (0or1).start: a two-element list[row, col]giving the starting cell.end: a two-element list[row, col]giving the target cell.
Output
An integer: the minimum number of moves, or -1 if no route exists. If start and end are the same cell, the answer is 0.
Constraints
1 <= m, n <= 1000- Every row of
gridhas the same lengthn. - Each entry of
gridis0or1. 0 <= start[0], end[0] < mand0 <= start[1], end[1] < n.grid[start[0]][start[1]] == 0andgrid[end[0]][end[1]] == 0.- The solution should run fast enough for grids with up to 10^6 cells.
Examples
Example 1
Input: fewest_moves([[0, 0, 0], [1, 1, 0], [0, 0, 0]], [0, 0], [2, 2])
Output: 4
Example 2
Input: fewest_moves([[0, 1], [1, 0]], [0, 0], [1, 1])
Output: -1
Example 3
Input: fewest_moves([[0, 0, 0], [0, 0, 0]], [0, 0], [1, 2])
Output: 3
Hints
Hint 1
Think of every open cell as a node in a graph, with an edge between each pair of adjacent open cells. Every edge costs exactly one move.
Hint 2
When all edges cost the same, a search that expands outward level by level reaches each cell by a shortest route the first time it sees it. Which traversal does that?
Hint 3
Mark a cell as seen at the moment you add it to the queue, not when you remove it, and handle start == end up front. Use a deque so removing from the front is O(1).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat each open cell as a node, with an edge between every two orthogonally adjacent open cells. Every edge has the same cost (one move), so this is a shortest-path problem on an unweighted graph, which breadth-first search (BFS) solves directly.
- If
startequalsend, return0. - Create a
distmatrix filled with-1. A value of-1means "not yet discovered"; any other value is the shortest known distance fromstart. - Set
dist[start] = 0and putstartin a queue. - Repeatedly remove the front cell. For each of its four neighbors that is inside the grid, open, and undiscovered:
- If the neighbor is
end, return the current distance plus one. - Otherwise record its distance and append it to the queue.
- If the neighbor is
- If the queue becomes empty,
endis unreachable, so return-1.
Why it is correct
BFS processes cells in non-decreasing order of distance: removing a cell at distance d only appends cells at distance d + 1, so the queue always holds distances in sorted order spanning at most two consecutive values. A cell is therefore first discovered from a cell at the smallest possible distance, which means its recorded distance is optimal. Because of that, returning as soon as end is discovered is safe. If end is never discovered, BFS has explored the whole connected region around start without finding it, so no path exists.
Marking cells as discovered when they are enqueued (rather than dequeued) ensures each cell enters the queue at most once. DFS would not be suitable here, since the first path it finds is not necessarily the shortest.
Complexity
- Time: O(m * n). Each cell is enqueued and dequeued at most once, with four neighbor checks each.
- Space: O(m * n) for the
distmatrix and the queue.
Reference solution
from collections import deque
from typing import List
def fewest_moves(grid: List[List[int]], start: List[int], end: List[int]) -> int:
rows, cols = len(grid), len(grid[0])
sx, sy = start
ex, ey = end
if (sx, sy) == (ex, ey):
return 0
dist = [[-1] * cols for _ in range(rows)]
dist[sx][sy] = 0
queue = deque([(sx, sy)])
while queue:
x, y = queue.popleft()
nd = dist[x][y] + 1
for nx, ny in ((x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)):
if 0 <= nx < rows and 0 <= ny < cols and grid[nx][ny] == 0 and dist[nx][ny] == -1:
if (nx, ny) == (ex, ey):
return nd
dist[nx][ny] = nd
queue.append((nx, ny))
return -1