Fewest Cells Through a Diagonal-Move Grid
Trees & GraphsAuto-graded · 19 test casesLast updated
Find the length of the shortest 8-directional clean-cell path across a square 0/1 grid using BFS.
You are given a square grid of size n x n filled with 0 (open) and 1 (blocked) cells. Standing on an open cell, you may step to any of the eight surrounding cells — up, down, left, right, and the four diagonals — as long as the destination exists inside the grid and holds a 0. Each step costs exactly one.
Return the number of cells in the shortest path that starts at the top-left cell (0, 0) and ends at the bottom-right cell (n-1, n-1), counting both endpoints. If no such path exists, return -1.
Details that matter:
- A path is only possible when both the start cell and the end cell are
0. Otherwise return-1. - A
1 x 1grid whose single cell is0yields1, because the start and end coincide. - The result counts cells visited, not edges, so a direct start-to-end walk has length
2and a single-cell grid has length1. - You may modify the input grid to track visited cells; this is allowed.
Constraints:
0 <= n <= 100grid[i][j]is either0or1gridis square, i.e. every row has lengthn- The grid may be empty (
n == 0), in which case the answer is-1
Examples
Example 1
Input: min_clear_cells_path([[0, 1], [1, 0]])
Output: 2
Example 2
Input: min_clear_cells_path([[0, 0, 0], [1, 1, 0], [1, 1, 0]])
Output: 4
Example 3
Input: min_clear_cells_path([[1, 0, 0], [1, 1, 0], [1, 1, 0]])
Output: -1
Hints
Hint 1
Every move costs the same, so a breadth-first search discovers cells in increasing order of distance — the first time you reach the target gives the minimum.
Hint 2
There are eight neighbor offsets to try, including the four diagonals; missing diagonals breaks cases like the 2x2 grid where only corner cells are open.
Hint 3
Mark a cell as visited the moment you push it onto the queue (e.g. by setting it to 1) so each cell is enqueued at most once, and handle a 1x1 grid separately since the target is the start itself.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Think of each open cell as a node in an unweighted graph, connected to its open neighbors in all eight directions. Since every edge has cost one, a breadth-first search from the start expands cells in non-decreasing order of path length, so the first time the end cell is reached the count is minimal.
Seed the queue with the start cell carrying a count of 1 (endpoints included). For each dequeued cell, examine the eight offsets. When a neighbor is inside the grid and open, mark it visited immediately (setting it to 1 reuses the grid in place) so it never enters the queue twice. If that neighbor is the target, return the current count plus one; otherwise enqueue it with count plus one. If the queue drains without reaching the target, return -1.
Why it is correct
BFS removes cells in order of increasing distance from the start, so any cell is first discovered through a shortest path. Marking on enqueue guarantees each reachable open cell is queued at most once, so its recorded count equals its true minimum. Returning on the first discovery of the target is therefore safe, and blocked or unreachable cells produce -1. The explicit checks for an empty grid, a blocked start or end, and the 1 x 1 case cover the situations the main loop does not.
Complexity
- Time: O(n²) — each open cell is enqueued once and does constant work over eight neighbors.
- Space: O(n²) for the queue in the worst case; no separate visited matrix is allocated because the grid is reused (the input is mutated).
from collections import deque
from typing import List
def min_clear_cells_path(grid: List[List[int]]) -> int:
n = len(grid)
if n == 0 or grid[0][0] != 0 or grid[n - 1][n - 1] != 0:
return -1
if n == 1:
return 1
queue = deque([(0, 0, 1)]) # (row, col, cells counted so far)
grid[0][0] = 1 # mark visited as soon as enqueued
directions = (
(-1, -1), (-1, 0), (-1, 1),
(0, -1), (0, 1),
(1, -1), (1, 0), (1, 1),
)
while queue:
row, col, steps = queue.popleft()
for dr, dc in directions:
nr, nc = row + dr, col + dc
if 0 <= nr < n and 0 <= nc < n and grid[nr][nc] == 0:
if nr == n - 1 and nc == n - 1:
return steps + 1
grid[nr][nc] = 1
queue.append((nr, nc, steps + 1))
return -1