Shortest Path in Binary Matrix

Medium

Description

Given an n x n binary matrix grid, return the length of the shortest clear path in the matrix. If there is no clear path, return -1. A clear path is from (0,0) to (n-1,n-1) only visiting cells with 0. You can move in 8 directions.

Examples

Input:grid = [[0,1],[1,0]]
Output:2
Explanation:

Path: (0,0) → (1,1).

Input:grid = [[0,0,0],[1,1,0],[1,1,0]]
Output:4
Explanation:

Shortest path has length 4.

Input:grid = [[0,0,0,0],[1,1,0,1],[0,1,0,0],[0,0,1,0]]
Output:6
Explanation:

The shortest clear path goes: (0,0) → (0,1) → (0,2) → (1,2) → (2,3) → (3,3). This demonstrates navigation around multiple obstacles using diagonal and straight moves.

Constraints

  • n == grid.length == grid[i].length
  • 1 ≤ n ≤ 100
  • grid[i][j] is 0 or 1

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!