 All Problems
Shortest Path in Binary Matrix
medium
graph
breadth-first search
matrix
amazon
google
facebook

Given an n × n binary matrix grid, return the length of the shortest clear path in the matrix. A clear path is a path from the top-left cell (0, 0) to the bottom-right cell (n-1, n-1) consisting of cells with value 0, where 8-directionally adjacent cells along the path are all 0. The length of a path is the number of visited cells.

If there is no clear path, return -1.

Example 1:

Input:
3
0 0 0
1 1 0
1 1 0
Output: 4

Example 2:

Input:
2
1 0
1 1
Output: -1

Constraints:

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

Input format: First line: n. Then n lines with n space-separated integers.

Output format: Shortest path length or -1.

Run to check your code against the sample cases, or submit to run every case