Shortest Path in Binary Matrix
Given an n x n binary matrix grid, return the length of the shortest clear path from top-left (0, 0) to bottom-right (n-1, n-1). A clear path visits only 0-cells and moves in 8 directions (horizontal, vertical and diagonal neighbours). The length is the number of cells on the path, including the start and end cells. Return -1 if no path exists.
Input: grid is a list of n lists, each holding n integers that are 0 or 1.
Example
0,1 1,0
2
gridis a matrix of 0s and 1s, where 0 means open and 1 means blocked:
The path must start at the top-left cell (row 0, column 0) and finish at the bottom-right cell (row 1, column 1).0 1 1 0- From any cell you may step to any of its 8 neighbours: up, down, left, right, or one of the four diagonals.
- The two straight neighbours of the start, (0, 1) and (1, 0), both hold 1, so neither is usable.
- The diagonal neighbour (1, 1) holds 0 and is the target itself, so a single diagonal step reaches it.
- Length counts cells on the path, not moves: the start plus the target gives , matching the output
2. - Notice that with only 4 directions this grid would have no clear path at all and the answer would be . Likewise, if either corner were 1, no path could exist.
Constraints
- 1 <= n <= 100
- grid[i][j] is 0 or 1