FastPrepShortest Path in a Binary Matrix

Shortest Path in a Binary Matrix

Meta logoMeta● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

Given an n x n binary matrix, return the number of cells in the shortest clear path from the top-left cell to the bottom-right cell.

A clear path visits only cells containing 0 and may move horizontally, vertically, or diagonally to any of the eight neighboring cells. Return -1 when no clear path exists.

Function

shortestPathBinaryMatrix(grid: int[][]) → int

Examples

Example 1

grid = [[0,1],[1,0]]return = 2

The two open corner cells are diagonal neighbors.

Example 2

grid = [[1,0],[0,0]]return = -1

The starting cell is blocked.

Constraints

  • 1 <= n <= 100
  • grid.length == grid[i].length == n
  • Every cell is 0 or 1.

More Meta problems

See Meta hiring insights
public int shortestPathBinaryMatrix(int[][] grid) {
    // Write your code here.
}
grid[[0,1],[1,0]]
expected2
Checking account…