KatInterview

Minimum Steps Across a Square Maze with Diagonal Moves

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

Last 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 is 1.

Constraints

  • The grid is n x n with n >= 0.
  • Each cell is either 0 (open) or 1 (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.