Shortest Path in Binary Matrix
Given an n x n binary matrix, a clear path runs from the top-left cell (0,0) to the bottom-right cell (n-1,n-1) through cells valued 0, moving in any of the 8 directions between adjacent (including diagonal) cells. Return the length of the shortest clear path measured in number of visited cells, or -1 if none exists.
Open official problem prompt ↗Compute the minimum number of cells on a clear top-left-to-bottom-right path where movement includes diagonals, or report that none exists.
A king on a chessboard walks from one corner to the opposite corner across open squares, taking one step per move in any of eight directions. You want the fewest squares the king must touch.
- Input
- grid = [[0,0,0],[1,1,0],[1,1,0]]
- Output
- 4
- Why
- The path (0,0) -> (0,1) -> (1,2) -> (2,2) visits 4 cells and is the shortest clear route to the corner.
n == grid.length == grid[i].length1 <= n <= 100grid[i][j] is 0 or 1