26 · Graphs: BFS & DFS

#1091 Shortest Path in Binary Matrix

Mediumsolve on LeetCode ↗

frequently reported atMetaAmazonGoogleMicrosoft

the problem

In plain words

In an n×n grid of 0s (open) and 1s (blocked), find the length of the shortest clear path from the top-left to the bottom-right, moving in 8 directions. Length counts cells. Return -1 if none exists.

in grid = [[0,1],[1,0]]

out 2

One diagonal step: 2 cells.

in grid = [[0,0,0],[1,1,0],[1,1,0]]

out 4

in grid = [[1,0,0],[1,1,0],[1,1,0]]

out -1

The start is blocked.

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

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #1730
      Shortest Path to Get Food
      Mediumin GraphsLeetCode Premium
    2. #994
      Rotting Oranges
      Mediumin Graphs
    3. #2290