Skip to content

Shortest Path in Binary Matrix

MediumGraphs
Decode it first. Clues, constraints, pattern and plan before any code.

You get an n x n grid of 0 (open) and 1 (blocked). Find a path from the top-left cell to the bottom-right cell that uses only open cells, where each move goes to one of the 8 neighbours (sides and diagonals). Return the number of cells on the shortest such path, or -1 if no path exists.

[[0, 1],
 [1, 0]]          →  2   (one diagonal step)
 
[[0, 0, 0],
 [1, 1, 0],
 [1, 1, 0]]       →  4
 
[[1, 0, 0],
 [1, 1, 0],
 [1, 1, 0]]       →  -1  (the start is blocked)

Constraints

  • 1 <= n <= 100
  • grid[i][j] is 0 or 1