Find the minimum number of cells in a valid path from the top-left to the bottom-right of a binary grid, moving in 8 directions through open cells only.
You are given an binary matrix grid where each cell is either 0 (open) or 1 (blocked).
A path starts at the top-left cell (0, 0) and ends at the bottom-right cell (n - 1, n - 1). From any cell, you may move to any of its 8 neighboring cells: horizontally, vertically, or diagonally adjacent.
A path is valid only if it visits open cells (0) and stays within the grid.
Return the length of the shortest valid path, measured as the number of cells visited along the path, including both the start and end cells. If no such path exists, return -1.
-1.grid: a 2D integer array of size n x ngrid[i][j] is 0 for an open cell or 1 for a blocked cell(0, 0) to (n - 1, n - 1), or -1 if unreachable1 <= ngrid is an n x n matrix0 or 1Example 1
Input
grid = [[0,1],[1,0]]
Output
2
Explanation
You can move diagonally from the top-left cell to the bottom-right cell.
Example 2
Input
grid = [[0,0,0],[1,1,0],[1,1,0]]
Output
4
Explanation
One shortest path is (0,0) -> (0,1) -> (1,2) -> (2,2), which visits 4 cells.
Example 3
Input
grid = [[1,0,0],[1,1,0],[1,1,0]]
Output
-1
Explanation
The starting cell is blocked, so no valid path exists.
Premium problem context
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.