Problems/1091. Shortest Path in Binary Matrix

1091. Shortest Path in Binary Matrix

MediumMatrix

Given an n x n binary grid, return the length of the shortest clear path from the top-left cell (0, 0) to the bottom-right cell (n - 1, n - 1). A clear path is a path of cells with value 0 such that adjacent cells share an edge or corner (8-directional connectivity). If there is no clear path, return -1.

Example 1
Input: grid = [ [0, 1, 0], [0, 0, 0], [1, 0, 0] ]
Output: 3
The shortest clear path is (0,0) -> (1,1) -> (2,2) which has a length of 3.
Example 2
Input: grid = [ [0, 1], [1, 1] ]
Output: -1
The exit (1,1) is blocked by a 1, so no clear path is possible.
Example 3
Input: grid = [ [0, 0, 0], [1, 1, 0], [1, 1, 0] ]
Output: 3
A clear path of length 3 is (0,0) -> (0,1) -> (1,2) -> (2,2).
Visualizer

Visualizer will appear here