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].length1 <= n <= 100grid[i][j] is 0 or 1See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI