MediumArrayBreadth-First SearchMatrix

1 approach, code in every language

Problem description

You are given an n x n binary grid. Each cell holds either 0, meaning it is open, or 1, meaning it is blocked.

A clear path runs from the top-left cell (0, 0) to the bottom-right cell (n - 1, n - 1). Every cell visited along the path must be open, and any two consecutive cells on the path must be connected in one of the eight directions (horizontally, vertically, or diagonally).

Return the length of the shortest such clear path, measured as the number of cells it visits. If no clear path exists, return -1.

Example 1

Input: grid = [[0,1],[1,0]]

Output: 2

The path visits (0, 0) and then its diagonal neighbor (1, 1), for a total of 2 cells.

Example 2

Input: grid = [[1,0,0],[1,1,0],[1,1,0]]

Output: -1

The start cell (0, 0) is blocked, so no clear path can even begin.

Constraints

  • n == grid.length == grid[i].length
  • 1 <= n <= 100
  • grid[i][j] is 0 or 1

After the pattern

Now solve one you haven't seen.

Fewest Tiles Across the Floor is our own problem on the technique behind Shortest Path in Binary Matrix: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free