Medium · Graphs

Shortest Path in Binary Matrix

Given an n × n binary matrix grid, return the length of the shortest clear path from the top-left cell to the bottom-right cell, counted in cells, where a clear path uses only 0-cells and moves between cells that share an edge or a corner. Return −1 if no clear path exists.

Examples

Example 1

{
  "grid": [
    [0, 0, 0],
    [1, 1, 0],
    [1, 1, 0]
  ]
}

Output: 4 cells

Example 2

{
  "grid": [
    [0, 1, 0],
    [0, 1, 0],
    [0, 0, 0]
  ]
}

Output: 4 cells

Rebuild it in the studio

Read every interview problem free. Ten rooms need no account. A token opens a problem in full — Pro never counts.

More Graphs problems