Skip to content

01 Matrix

Find each cell's distance to the nearest 0 with one BFS that starts from every 0 at once.

MediumGraph BFS and DFS
Solve on LeetCode

The problem

You get a grid mat of 0s and 1s that contains at least one 0. For every cell, find the distance to the nearest 0, where one step moves up, down, left or right. Return a grid of the same size that holds these distances.

Input mat = [[1, 1, 1], [1, 0, 1], [1, 1, 1]]

Output [[2, 1, 2], [1, 0, 1], [2, 1, 2]]

The middle cell is the only 0. The cells beside it are 1 step away and the corners are 2 steps away.

Input mat = [[0, 1, 1, 1]]

Output [[0, 1, 2, 3]]

In a single row the distance grows by one per cell.

Key constraint: The grid can hold up to 10,000 cells, so a separate search from every cell, at up to 10,000 steps each, is too slow.

How to spot the pattern

  • You need a shortest distance for every cell, measured in grid steps.
  • There are many possible targets (every 0), and each cell only cares about the nearest one.

The idea

Instead of searching outward from every 1 for a 0, search outward from all the 0s together. Put every 0 in the queue with distance 0 and run BFS: the first time the search reaches a cell, it arrives along a shortest path from the nearest 0, so that distance is final. Each cell is reached exactly once, which makes the whole thing O(m * n).

Brute force: Run a separate BFS from each cell until it meets a 0, which costs O((m * n)^2) time in the worst case.

Step by step

  1. 1Make a dist grid filled with -1, which means not reached yet.
  2. 2Set dist to 0 for every 0 cell and put all of those cells in a queue.
  3. 3Take a cell from the queue and look at its four neighbors.
  4. 4For each neighbor still at -1, set its distance to the current cell's distance plus 1 and add it to the queue.
  5. 5When the queue is empty, return dist.

See the pattern move

The graph bfs and dfs pattern on a small example. Step through it, or press play.

Code

from collections import deque


class Solution:
    def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:
        rows, cols = len(mat), len(mat[0])
        dist = [[-1] * cols for _ in range(rows)]  # -1 means not reached yet
        queue = deque()
        for r in range(rows):
            for c in range(cols):
                if mat[r][c] == 0:
                    dist[r][c] = 0
                    queue.append((r, c))  # every 0 is a starting point

        while queue:
            r, c = queue.popleft()
            for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
                if 0 <= nr < rows and 0 <= nc < cols and dist[nr][nc] == -1:
                    dist[nr][nc] = dist[r][c] + 1  # the first visit is the shortest
                    queue.append((nr, nc))
        return dist

Complexity

Time

O(m * n)

Space

O(m * n)

Each cell enters the queue once and checks four neighbors; the distance grid and the queue hold up to m * n cells.

Watch out for

  • Starting the BFS from the 1s, or from one 0 at a time, which repeats work and can leave a cell with the distance to a 0 that is not the nearest.
  • Writing distances into mat with no way to tell an unvisited 1 from a cell at distance 1; a separate grid or a -1 marker avoids that.
  • Setting a cell's distance when you take it out of the queue instead of when you add it, so the same cell can be queued many times.

Follow-up questions

Can you solve it without a queue?

Yes, with two DP passes: top-left to bottom-right taking the minimum from the top and left neighbors, then bottom-right to top-left using the bottom and right neighbors. It also runs in O(m * n).

What if some cells were walls you can't walk through?

The same multi-source BFS still works if it never enters a wall. The two-pass DP does not, because a shortest path may have to bend around walls.

In Hinglish

Har 1 se 0 dhoondne ke bajaye, saare 0 ek saath queue mein daalo aur BFS chalao. Jo cell pehli baar pahuncha, uski distance wahi final hai.

Related problems