01 Matrix (LeetCode 542): Solution and Explanation

Medium
Array
Dynamic Programming
Breadth First Search
Matrix

Given a grid of 0s and 1s, replace every cell with its distance to the nearest 0, where one step moves up, down, left or right. Cells that are already 0 stay 0.

Intuition

The direct idea is to run a BFS from every 1 until it finds a 0. Each search is correct, but a grid with many 1s far from any 0 repeats almost the same search over and over, which costs O((m*n)^2) in the worst case.

Flip the direction. Distances are symmetric, so the distance from a cell to its nearest 0 equals the distance from that nearest 0 to the cell. Start the search from the zeros instead.

Put every 0 in the queue before the search begins. BFS then expands in waves: all cells at distance 1 from some zero, then all cells at distance 2, and so on. When a wave first touches a cell, no zero can be closer, because a closer zero's wave would have arrived earlier. That first touch is the answer, so each cell is written once.

Approach: Multi-source BFS

  1. Create a dist grid filled with -1 to mean not reached yet.
  2. Scan the matrix. For every 0, set dist to 0 and push the cell onto the queue.
  3. Pop a cell (r, c). For each of its four neighbours that is inside the grid and still -1, set its distance to dist[r][c] + 1 and push it.
  4. Repeat until the queue is empty, then return dist.

Step-by-step example

mat = [[0,0,0],[0,1,0],[1,1,1]]
  1. Five cells hold 0, so all five start in the queue with distance 0.
  2. Popping (0,1) reaches (1,1) first, which gets distance 1. Popping (1,0) reaches (2,0) with distance 1, and (1,2) reaches (2,2) with distance 1.
  3. The distance 1 cells come out next. (1,1) reaches (2,1) and gives it distance 2. (2,0) and (2,2) find all their neighbours already set.
  4. (2,1) is popped last and changes nothing. The queue is empty, and the answer is [[0,0,0],[0,1,0],[1,2,1]].

Code: Python, Java, C++

1class Solution:
2    def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:
3        m, n = len(mat), len(mat[0])
4        dist = [[-1] * n for _ in range(m)]
5        queue = deque()
6        for r in range(m):
7            for c in range(n):
8                if mat[r][c] == 0:
9                    dist[r][c] = 0
10                    queue.append((r, c))
11        while queue:
12            r, c = queue.popleft()
13            for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
14                nr, nc = r + dr, c + dc
15                if 0 <= nr < m and 0 <= nc < n and dist[nr][nc] == -1:
16                    dist[nr][nc] = dist[r][c] + 1
17                    queue.append((nr, nc))
18        return dist
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(m * n)

Every cell is pushed and popped at most once, and each pop looks at four neighbours.

Space

O(m * n)

The distance grid has one entry per cell, and the queue can hold a large share of the cells at once.

Other approaches

Two-pass dynamic programming (time O(m * n), space O(1) extra beyond the output)

Sweep top-left to bottom-right taking the minimum from the top and left neighbours, then sweep bottom-right to top-left using the bottom and right neighbours. Any shortest path can be split into those two monotone directions, so two passes are enough and no queue is needed.

BFS from every 1 (time O((m * n)^2), space O(m * n))

Search outward from each 1 until a 0 is found. It is easy to reason about but repeats overlapping searches and is far too slow on large grids of 1s.

Common mistakes

  • Seeding the queue with only one 0. Every zero has to start together, or the first visit is no longer guaranteed to come from the nearest zero.
  • Marking cells visited when they are popped instead of when they are pushed, which lets the same cell enter the queue several times.
  • Using 0 as the not-visited marker, which collides with the real distance of zero cells. Use -1 or infinity.
  • In JavaScript, calling shift() on an array queue for a 10,000 cell grid. A moving head index keeps each pop O(1).

Frequently asked questions

Why does starting from all zeros at once give the shortest distance?

BFS from several sources behaves like BFS from one imaginary node connected to every zero. It still visits cells in order of distance, so the first time a cell is reached is from its nearest zero.

Is this the same idea as Rotting Oranges or Walls and Gates?

Yes. All three put every starting cell in the queue first and let the wave spread outward. Here the starting cells are the zeros and the wave writes distances.

Can I avoid the extra queue memory?

The two-pass DP version uses only the output grid. It fills in distances from the top and left first, then fixes them with a pass from the bottom and right.

What is the time complexity of the multi-source BFS?

O(m * n). Each cell enters the queue once and each pop checks four neighbours, so the work is linear in the number of cells.