MediumArrayBreadth-First SearchMatrixUpdated Sep 2026

1091. Shortest Path in a Binary Matrix

Asked at Databricks, Anduril

Difficulty

Medium

Time

O(n^2)

Space

O(n^2)

Pattern

Array

Companies

2

Problem

You are given an n x n grid filled with 0s and 1s. A 0 is an open cell you may walk on, and a 1 is a blocked cell you must avoid.

Find the shortest clear path from the top-left cell (0, 0) to the bottom-right cell (n-1, n-1). A path is clear when every cell on it is 0. From one cell you may step to any of the 8 neighbors — the cells that share an edge or a corner with it. The length of a path is the number of cells it visits, counting both the start and the end cell.

Return the length of the shortest clear path. If no clear path exists, return -1. Note that if the start cell or the end cell is 1, no path can exist, so the answer is -1.

Walk from corner to corner on zeros

grid01010110The green cell is the start, the orange cell is thegoal; the two 1s are blocked.path01010110They touch at a corner, so one diagonal step connectsthem and the path length is 2.
Start at the top-left, end at the bottom-right, and only step on 0 cells — diagonals are allowed.

Constraints

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

Examples

Example 1
Inputgrid = [[0,1],[1,0]]
Output2
WhyThe start (0,0) and the end (1,1) are diagonal neighbors, so we can jump straight from one to the other. The path visits 2 cells.
Example 2
Inputgrid = [[0,0,0],[1,1,0],[1,1,0]]
Output4
WhyThe only way through is along the right side: (0,0) → (0,1) → (0,2) → (1,2) → (2,2). That is 4 cells, and no shorter route exists because the left and middle columns are blocked.
Example 3
Inputgrid = [[1,0,0],[1,1,0],[1,1,0]]
Output-1
WhyThe start cell (0,0) is 1, so we cannot even stand on it. No clear path exists.

Asked At

2 companies
CompanyDifficulty
DatabricksMediumView all Databricks questions →
AndurilMediumView all Anduril questions →

How to Think About It

1

Why BFS? In an unweighted grid, BFS explores all cells at distance 1 before distance 2, and so on. The first time you reach the bottom-right cell, you have the shortest path. DFS would explore one path to the end before backtracking, which doesn't guarantee shortest path.

2

Setup: use a queue, start at (0, 0) with path length 1. Mark (0, 0) as visited (set matrix[0][0] = 1). For each cell, explore all 8 neighbors. If a neighbor is within bounds, is 0 (open), and unvisited, enqueue it with path length + 1.

3

8-direction movement: use a directions array: [(-1,-1), (-1,0), (-1,1), (0,-1), (0,1), (1,-1), (1,0), (1,1)]. This covers all adjacent cells including diagonals.

4

Early termination: as soon as you pop (n-1, n-1) from the queue, return the path length. BFS guarantees this is optimal. Time: O(n²) since each cell is visited at most once. Space: O(n²) for the queue and visited set.

Optimal Approach

BFS from (0, 0). Use a queue storing (row, col, distance). Start by enqueueing (0, 0, 1) and marking matrix[0][0] = 1.

While queue is not empty:

  1. Dequeue (r, c, dist).
  2. If r == n-1 and c == n-1, return dist.
  3. For each of the 8 neighbors (nr, nc):
    • If in bounds, matrix[nr][nc] == 0: mark as visited, enqueue (nr, nc, dist + 1).
  4. If queue empties without reaching destination, return -1.

Walkthrough: matrix = [[0,1],[1,0]]. Start (0,0) dist=1. Neighbors of (0,0): (0,1)=1 skip, (1,0)=1 skip, (1,1)=0 enqueue (1,1,2). Pop (1,1,2). It's the destination. Return 2.

Time: O(n²). Space: O(n²).

BFS spreads out in rings

grid01010110Step 1 — push the start (0,0) with distance 1 and markit visited.grid01011110Step 2 — the 1s are skipped, but the diagonal neighbor(1,1) is open, so it is pushed with distance 2.pop (r, c, dist)if r == n-1 and c == n-1: return distpush each open neighbor with dist + 1
BFS visits all cells at distance 1, then distance 2, and so on, so the first time it reaches the goal the distance is minimal.
ComplexityTime O(n^2)Space O(n^2)Each of the n^2 cells enters the queue at most once, and the queue plus the visited marks can hold up to n^2 cells.

What Trips People Up in Real Interviews

1

Using DFS instead of BFS. DFS finds a path, not the shortest path. You must use BFS for unweighted shortest path problems. This is the single most important distinction.

2

Forgetting to mark cells as visited when enqueuing, not when dequeuing. If you mark on dequeue, other paths might enqueue the same cell before it's processed, leading to duplicate work and wrong results.

3

Off-by-one in path length. Start with length 1 (the starting cell). Each neighbor adds 1. If you start with length 0, your answer will be off by 1.

4

Not checking if the start or end cell is blocked. If matrix[0][0] = 1 or matrix[n-1][n-1] = 1, return -1 immediately. BFS would never reach the destination.

5

Using a hash set for visited instead of modifying the matrix. Modifying the matrix in-place is cleaner and saves O(n²) space. Just set matrix[i][j] = 1 when visited. Since the matrix is binary, 1 already means blocked, so it doubles as visited.

Solution Code

O(n^2) time
from collections import deque

def shortestPathBinaryMatrix(grid):
    n = len(grid)
    if grid[0][0] == 1 or grid[n - 1][n - 1] == 1:
        return -1
    directions = [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)]
    queue = deque([(0, 0, 1)])
    grid[0][0] = 1
    while queue:
        r, c, dist = queue.popleft()
        if r == n - 1 and c == n - 1:
            return dist
        for dr, dc in directions:
            nr, nc = r + dr, c + dc
            if 0 <= nr < n and 0 <= nc < n and grid[nr][nc] == 0:
                grid[nr][nc] = 1
                queue.append((nr, nc, dist + 1))
    return -1

Pro at DSA?

Test your skills with a real FAANG-style mock interview.

Start a Mock Interview →

Frequently Asked Questions

What is the Shortest Path in a Binary Matrix problem?

Given an n x n binary matrix (0 = open, 1 = blocked), find the shortest path from top-left to bottom-right. You can move in 8 directions. BFS guarantees the shortest path in an unweighted grid, making this a straightforward application of the BFS pattern.

How do you solve Shortest Path in a Binary Matrix?

The optimal approach runs in O(n^2) time and O(n^2) space. Scroll up to "Optimal Approach" for the step-by-step walkthrough, diagrams, and code in Python, C++ and Java.

What companies ask Shortest Path in a Binary Matrix?

Shortest Path in a Binary Matrix is asked at Databricks, Anduril. It is a medium difficulty problem.

What are common mistakes on Shortest Path in a Binary Matrix?
  • Using DFS instead of BFS. DFS finds *a* path, not the *shortest* path. You must use BFS for unweighted shortest path problems. This is the single most important distinction.
  • Forgetting to mark cells as visited when enqueuing, not when dequeuing. If you mark on dequeue, other paths might enqueue the same cell before it's processed, leading to duplicate work and wrong results.
  • Off-by-one in path length. Start with length 1 (the starting cell). Each neighbor adds 1. If you start with length 0, your answer will be off by 1.
  • Not checking if the start or end cell is blocked. If `matrix[0][0]` = 1 or `matrix[n-1][n-1]` = 1, return -1 immediately. BFS would never reach the destination.
  • Using a `hash set` for visited instead of modifying the matrix. Modifying the matrix in-place is cleaner and saves `O(n²)` space. Just set `matrix[i][j]` = 1 when visited. Since the matrix is binary, 1 already means blocked, so it doubles as visited.