Minimum Steps Across a Square Maze with Diagonal Moves
Trees & GraphsAuto-graded · 18 test casesLast updated
Tests breadth-first search on a square binary grid with eight-directional moves, handling blocked endpoints, visited tracking, and counting cells along the shortest route.
You are given a square maze represented as an n x n grid of integers. A cell containing 0 is open and can be stepped on; a cell containing 1 is a wall and cannot be entered.
Starting in the top-left cell (0, 0), you want to reach the bottom-right cell (n-1, n-1). From any cell you may move to any of its up to 8 neighbors: the four orthogonal neighbors (up, down, left, right) and the four diagonal neighbors. Every cell on your route, including the start and the destination, must be open.
Return the number of cells on the shortest such route, counting both the starting cell and the destination cell. If the start or the destination is a wall, or if no route exists, return -1.
Additional rules:
- Diagonal moves are always allowed between two open cells, even if the two orthogonally adjacent cells that share the corner are walls.
- If the grid is empty, or is not square, return
-1. - A grid with a single open cell (
[[0]]) has a route consisting of just that one cell, so the answer is1.
Constraints
- The grid is
n x nwithn >= 0. - Each cell is either
0(open) or1(wall). - Every move has the same cost, one step to a neighboring cell.
- The returned length counts cells, not moves between them.
- The input grid may be modified, but it is not required.
Examples
Example 1
Input: min_cells_to_exit([[0, 1], [1, 0]])
Output: 2
Example 2
Input: min_cells_to_exit([[0, 0, 0], [1, 1, 0], [1, 1, 0]])
Output: 4
Example 3
Input: min_cells_to_exit([[1, 0], [0, 0]])
Output: -1
Hints
Hint 1
Every move costs the same, so think about which traversal order discovers cells in increasing order of distance from the start.
Hint 2
Check the two endpoint cells before doing any searching, and store the current route length (in cells) alongside each queued cell.
Hint 3
Mark a cell as seen at the moment you enqueue it, not when you dequeue it, so that no cell is queued more than once. The first time you dequeue the bottom-right cell, its length is the answer.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat each open cell as a node in an unweighted graph, with an edge to each of its open neighbors among the 8 surrounding cells. The task is then the shortest path between two nodes in an unweighted graph, which is what breadth-first search (BFS) solves.
- Validate the input. If the grid is empty or not square, return
-1. If the top-left or bottom-right cell is a wall, return-1. - Start a queue with the start cell and a route length of
1(the start cell itself counts). - Repeatedly remove a cell from the front of the queue. If it is the bottom-right cell, return its route length.
- Otherwise, look at all 8 neighbors. For each one that is in bounds, open, and not yet seen, mark it as seen and enqueue it with length one greater.
- If the queue empties without reaching the destination, return
-1.
Why it is correct
BFS processes cells in non-decreasing order of their distance from the start. The queue always holds cells whose lengths differ by at most one, and all cells of length k are processed before any cell of length k + 1. So the first time the destination is dequeued, no shorter route can exist. Marking a cell as seen when it is enqueued guarantees it is queued once, with its smallest possible length, and prevents cycles. Endpoint checks handle the cases where the start or end is blocked, and the single-cell grid [[0]] returns 1 immediately because the start is the destination.
Complexity
- Time:
O(n^2). Each cell is enqueued at most once and examines a constant 8 neighbors. - Space:
O(n^2)for the queue and the seen set in the worst case.
Reference solution
from collections import deque
from typing import List
def min_cells_to_exit(maze: List[List[int]]) -> int:
n = len(maze)
if n == 0 or any(len(row) != n for row in maze):
return -1
if maze[0][0] != 0 or maze[n - 1][n - 1] != 0:
return -1
moves = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]
queue = deque([(0, 0, 1)])
seen = {(0, 0)}
while queue:
r, c, length = queue.popleft()
if r == n - 1 and c == n - 1:
return length
for dr, dc in moves:
nr, nc = r + dr, c + dc
if 0 <= nr < n and 0 <= nc < n and maze[nr][nc] == 0 and (nr, nc) not in seen:
seen.add((nr, nc))
queue.append((nr, nc, length + 1))
return -1