Skip to content
Decoder

Shortest Path in Binary Matrix

Medium

Problem

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.

Example 1

[[0, 1],

Example 2

Input
[1, 0]]
Output
2
Why
one diagonal step

Example 3

[[0, 0, 0],

Example 4

 [1, 1, 0],

Example 5

Input
[1, 1, 0]]
Output
4

Example 6

[[1, 0, 0],

Example 7

 [1, 1, 0],

Example 8

Input
[1, 1, 0]]
Output
-1
Why
the start is blocked

Constraints

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

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.