iq.lab
Python starts when a code cell comes near or you run one
mediumBreadth-first search target 25 min

Shortest clear path in a grid

A square grid grid has n rows and n columns. A cell holding 0 is open and a cell holding 1 is blocked. You start on the top-left cell and want to reach the bottom-right cell, stepping only on open cells. From a cell you may step to any of its 8 neighbors: up, down, left, right, or one of the four diagonals.

Return the number of cells on the shortest such path, counting the first and the last cell. Return -1 when there is no path, which includes the case where the start or the end cell is blocked. A 1 × 1 open grid is a path of one cell, so its answer is 1. You may change grid while you work.

Cells are written (row, column), counting from 0.

Example 1
Inputgrid = [[0, 1, 0], [0, 1, 0], [0, 0, 0]]Output4

Down to (1, 0), diagonally to (2, 1), then right to (2, 2). A path of 3 cells would need the center cell, which is blocked.

Example 2
Inputgrid = [[0, 0, 1], [1, 1, 1], [0, 0, 0]]Output-1

The middle row is blocked all the way across, and a diagonal step still has to land on an open cell.

Example 3
Inputgrid = [[1, 0], [0, 0]]Output-1

The start cell is blocked.

Constraints
  • 1 ≤ n ≤ 100

  • Every cell is 0 or 1.

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.