Shortest Path in Binary Matrix

Given an n x n binary grid, return the length of the shortest clear path from the top-left cell to the bottom-right cell using 8-directional movement. Pattern focus: BFS shortest path. Track distance by layers, stop as soon as the target is reached, and handle blocked start or end cells correctly.

Input Format

grid = binary matrix where 0 is open and 1 is blocked

Output Format

shortest path length from top-left to bottom-right, or -1 if impossible

Constraints

  • 1 <= n <= 100
  • Each grid cell is 0 or 1.
  • Movement is allowed in 8 directions.

Examples

Example 1:

Input:

grid = [[0,1],[1,0]]

Output:

2

Explanation:

The diagonal move reaches the target in two cells.

Example 2:

Input:

grid = [[1]]

Output:

-1

Explanation:

The start cell is blocked.

Example 3:

Input:

grid = [[0,0,0],[1,1,0],[1,1,0]]

Output:

4

Explanation:

A valid 8-direction path exists around the blocked cells.

Loading...
Shortest Path in Binary Matrix - Shortest Path