Community Problem

Shortest Path in Binary Matrix

Difficulty: Medium

BFS through 0-cells in 8 directions to find the shortest path from top-left to bottom-right.

Shortest Path in Binary Matrix

BFS through 0-cells in 8 directions to find the shortest path from top-left to bottom-right.

MEDIUM
Free
graphs
bfs
matrix-algorithms
shortest-path
nehanasser

By @nehanasser

May 1, 2026

·

Updated May 18, 2026

1,188 views

6

4.2 (13)

I had this on a Lyft onsite and the gotcha was the 8-directional move set; most candidates default to 4-direction grid BFS and silently undercount paths. The catalog covers BFS and Matrix Algorithms, but it skipped this 8-direction variant which is the textbook "why is BFS the right tool for unweighted shortest path?" question.

Shortest Path in Binary Matrix

Given an n x n binary matrix grid, return the length of the shortest clear path in the matrix. If there is no clear path, return -1.

A clear path in a binary matrix is a path from the top-left cell (0, 0) to the bottom-right cell (n - 1, n - 1) such that:

  • All the visited cells of the path are 0.
  • All the adjacent cells of the path are 8-directionally connected (i.e. they differ by at most 1 in row and column).

The length of a clear path is the number of visited cells of this path.

Examples

Example 1:

  • Input: grid = [[0, 1], [1, 0]]
  • Output: 2
  • Explanation: Go diagonally from (0, 0) to (1, 1). Two cells visited.

Example 2:

  • Input: grid = [[0, 0, 0], [1, 1, 0], [1, 1, 0]]
  • Output: 4
  • Explanation: One shortest path is (0,0) -> (0,1) -> (1,2) -> (2,2), four cells in total. The diagonal hop from (0,1) to (1,2) is allowed because the move is 8-directional.

Example 3:

  • Input: grid = [[1, 0, 0], [1, 1, 0], [1, 1, 0]]
  • Output: -1
  • Explanation: The starting cell (0, 0) is 1. No clear path exists.

Example 4:

  • Input: grid = [[0]]
  • Output: 1
  • Explanation: Single-cell grid: the only path is one step.

Constraints

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

Follow-up

Why BFS? On an unweighted graph (every move costs 1), BFS yields shortest paths because cells are dequeued in order of their distance from the source. Dijkstra would also work but is overkill for unit-weight edges; A* with the Chebyshev-distance heuristic is even faster in practice.

Solution

Hints

0/4
Hint 1
Hint 2
Hint 3
Hint 4
All Problems