KatInterview

Fewest Cells Through a Diagonal-Move Grid

Trees & GraphsAuto-graded · 19 test cases
MediumAuto-gradedTrees & Graphsbfsgridshortest-path

Last 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 1 grid whose single cell is 0 yields 1, because the start and end coincide.
  • The result counts cells visited, not edges, so a direct start-to-end walk has length 2 and a single-cell grid has length 1.
  • You may modify the input grid to track visited cells; this is allowed.

Constraints:

  • 0 <= n <= 100
  • grid[i][j] is either 0 or 1
  • grid is square, i.e. every row has length n
  • 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.