Skip to content

Shortest Path in Binary Matrix

Count the cells on the shortest clear path across a 0/1 grid when you may step in all 8 directions.

MediumShortest Paths
Solve on LeetCode

The problem

You get an n x n grid of 0s and 1s. A clear path starts at the top-left cell, ends at the bottom-right cell, uses only cells that hold 0, and moves between cells that touch at a side or a corner (8 directions). Return the number of cells on the shortest clear path, or -1 if there is none.

Input grid = [[0, 0, 0, 1], [1, 1, 0, 1], [1, 1, 0, 0], [1, 1, 1, 0]]

Output 5

One shortest path is (0, 0), (0, 1), (1, 2), (2, 3), (3, 3). The diagonal steps cut the corners.

Input grid = [[0, 1, 0], [1, 1, 0], [0, 0, 0]]

Output -1

All three cells touching the start hold 1, so you can't take a single step.

Key constraint: The grid is at most 100 x 100, so visiting each cell once is cheap, but trying every possible path is not.

How to spot the pattern

  • You need the fewest steps from one cell to another, and every step costs the same.
  • You move on a grid with blocked cells, here in 8 directions.
  • Each cell only needs to be reached once, the first time, by the shortest way.

The idea

BFS explores the grid in rings: first every cell 1 step from the start, then every cell 2 steps away, and so on. So the first time BFS reaches a cell, it has found the shortest way there, and the first time it reaches the bottom-right corner, that distance is the answer. Mark each cell the moment you discover it, so it joins the queue only once.

Brute force: Try every path with DFS and keep the shortest, which takes exponential time on an open grid.

Step by step

  1. 1If the start or the end cell holds 1, return -1 straight away.
  2. 2Keep a dist grid where 0 means not reached yet, set dist[0][0] = 1 and put the start in a queue.
  3. 3Pop a cell from the front of the queue; if it is the bottom-right corner, return its distance.
  4. 4For each of its 8 neighbors that is inside the grid, holds 0 and is not reached yet, set its distance to one more and push it.
  5. 5If the queue runs empty first, the end can't be reached, so return -1.

See the pattern move

The shortest paths pattern on a small example. Step through it, or press play.

Code

from collections import deque


class Solution:
    def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
        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)]
        # dist[r][c] = cells on the shortest path to (r, c); 0 means not reached yet
        dist = [[0] * n for _ in range(n)]
        dist[0][0] = 1
        queue = deque([(0, 0)])
        while queue:
            r, c = queue.popleft()
            if r == n - 1 and c == n - 1:
                return dist[r][c]
            for dr, dc in directions:
                nr, nc = r + dr, c + dc
                if 0 <= nr < n and 0 <= nc < n and grid[nr][nc] == 0 and dist[nr][nc] == 0:
                    dist[nr][nc] = dist[r][c] + 1  # mark it now, so it joins the queue only once
                    queue.append((nr, nc))
        return -1

Complexity

Time

O(n^2)

Space

O(n^2)

Each of the n^2 cells enters the queue at most once and checks 8 neighbors; the dist grid and the queue hold up to n^2 cells.

Watch out for

  • Marking a cell as visited when you pop it instead of when you push it, so the same cell enters the queue many times.
  • Counting steps instead of cells: the path length counts the start cell, so a 1 x 1 grid holding 0 has the answer 1.
  • Using DFS: it finds a path, but not necessarily the shortest one.

Follow-up questions

How would you return the path itself, not just its length?

When you first reach a cell, record the cell you came from. At the end, walk these parents back from the corner to the start and reverse the list.

What if a diagonal step cost more than a straight one?

Steps no longer cost the same, so BFS is not enough. Use Dijkstra with a min-heap, as in Network Delay Time.

In Hinglish

BFS ring ki tarah failta hai, isliye jo cell pehli baar mila, wahi uska sabse chhota raasta hai. Cell ko queue mein daalte hi mark kar do, warna woh baar baar aayega.

Related problems