LeetCode #542 Medium

01 Matrix

01 Matrix is LeetCode 542 (Medium). You get an m x n grid mat of 0s and 1s. Return a grid of the same size where each cell holds the distance to its nearest 0.

  • One step moves to a cell that shares an edge (up, down, left or right), so distance counts those steps.
  • A 0 cell has distance 0, and the grid always contains at least one 0.
  • m * n is at most 10⁴, so the answer should touch each cell a constant number of times.
Constraints
  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n <= 10⁴
  • 1 <= m * n <= 10⁴
  • mat[i][j] is either 0 or 1.
  • There is at least one 0 in mat.
bfsgridmulti-source
Open on LeetCode ↗
02

Intuition

Searching outward from every 1 until it finds a 0 repeats the same work for neighbouring cells and can cost O((m·n)²). Turn the question around: let all the 0s spread outward together.

  • Layers: a BFS that starts with every 0 in its queue first reaches all cells at distance 1, then all cells at distance 2, and so on.
  • First visit wins: so the first time the wave reaches a cell, it came from that cell's nearest 0. That distance is final; no later visit can beat it.

This is multi-source BFS: many starting points, one search, and the BFS layer number is the answer.

How to spot this pattern

This problem is the textbook case for multi-source BFS. Reach for it when every cell needs its distance to the nearest of many targets in an unweighted grid or graph. Rotting Oranges (994), Walls and Gates (286) and As Far from Land as Possible (1162) are the same search with different sources.

03

Approach

Try it first

Before reading on: in [[0,0,0],[0,1,0],[1,1,1]], which cells are 1 step from a 0, and which is 2? Then think about which cells should be in the queue before the search starts.

1

Queue every 0 at distance 0

Make dist the size of mat, filled with -1 for "not reached yet". Scan the grid once; for every 0, set dist = 0 and push the cell. A separate value for "not reached" matters because 0 is a real distance here.

2

Pop a cell and reach its neighbours

Pop (r, c) from the front of the queue. For each of its four neighbours inside the grid with dist == -1:

  • set its distance to dist[r][c] + 1;
  • push it to the back of the queue.

Write the distance when you push, not when you pop, so a cell next to two queued cells is still pushed only once.

3

Return when the queue is empty

The queue holds every distance-d cell before any distance-d+1 cell, so each cell is first reached from its nearest 0 and is never changed again. When the queue empties, every cell has its answer.

04

Code in Python, C++ and Java

▶1from collections import deque
▶2 
▶3class Solution:
▶4 def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:
▶5 m, n = len(mat), len(mat[0])
▶6 dist = [[-1] * n for _ in range(m)]
▶7 q = deque()
▶8 for r in range(m):
▶9 for c in range(n):
▶10 if mat[r][c] == 0:
▶11 dist[r][c] = 0
▶12 q.append((r, c))
▶13 while q:
▶14 r, c = q.popleft()
▶15 for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
▶16 if 0 <= nr < m and 0 <= nc < n and dist[nr][nc] == -1:
▶17 dist[nr][nc] = dist[r][c] + 1
▶18 q.append((nr, nc))
▶19 return dist
mat012000010102111queueemptyfind each cell's distance to the nearest 0
grid3 × 34 cells hold a 1
dist-1 everywheremeans not reached yet
Running a separate search from every 1 would cover the same cells again and again. Instead, start from every 0 at once and spread outward. The code fills dist with -1 first, so "not reached yet" can never be confused with a real distance of 0.
dist01200001002queue0,00,10,21,01,2seed: 5 zeros → distance 0, all queued
queue5every 0, together
not reached4dashed cells
Each 0 is its own nearest 0, so it gets distance 0 and joins the queue. Putting all of them in before the search starts is what lets one BFS answer every cell: the wave grows from all zeros in step.
dist01200001002queue0,10,21,01,2pop (0,0) → nothing new
popped(0,0)distance 0
newnoneall neighbours set
queue4cells waiting
Pop (0,0) at distance 0. Every neighbour already has a distance, so nothing new is queued.
dist012000010102queue0,21,01,21,1pop (0,1) → (1,1) = 1
popped(0,1)distance 0
new(1,1)distance 1
queue4cells waiting
Pop (0,1) at distance 0. Neighbour (1,1) was not reached yet, so it gets 1 and joins the back of the queue. The distance is written when the cell is queued, so no other cell can queue it a second time.
dist012000010102queue1,01,21,1pop (0,2) → nothing new
popped(0,2)distance 0
newnoneall neighbours set
queue3cells waiting
Pop (0,2) at distance 0. Every neighbour already has a distance, so nothing new is queued.
dist0120000101021queue1,21,12,0pop (1,0) → (2,0) = 1
popped(1,0)distance 0
new(2,0)distance 1
queue3cells waiting
Pop (1,0) at distance 0. Neighbour (2,0) was not reached yet, so it gets 1 and joins the back of the queue. The distance is written when the cell is queued, so no other cell can queue it a second time. (1,1) was already reached by an earlier cell in the queue, with the same distance 1, so it is left alone (grey dashed arrow).
dist01200001010211queue1,12,02,2pop (1,2) → (2,2) = 1
popped(1,2)distance 0
new(2,2)distance 1
queue3cells waiting
Pop (1,2) at distance 0. Neighbour (2,2) was not reached yet, so it gets 1 and joins the back of the queue. The distance is written when the cell is queued, so no other cell can queue it a second time. (1,1) was already reached by an earlier cell in the queue, with the same distance 1, so it is left alone (grey dashed arrow).
dist012000010102121queue2,02,22,1pop (1,1) → (2,1) = 2
popped(1,1)distance 1
new(2,1)distance 2
queue3cells waiting
Pop (1,1) at distance 1. Neighbour (2,1) was not reached yet, so it gets 2 and joins the back of the queue. The distance is written when the cell is queued, so no other cell can queue it a second time.
dist012000010102121queue2,22,1pop (2,0) → nothing new
popped(2,0)distance 1
newnoneall neighbours set
queue2cells waiting
Pop (2,0) at distance 1. Every neighbour already has a distance, so nothing new is queued. (2,1) was already reached by an earlier cell in the queue, with the same distance 2, so it is left alone (grey dashed arrow).
dist012000010102121queue2,1pop (2,2) → nothing new
popped(2,2)distance 1
newnoneall neighbours set
queue1cells waiting
Pop (2,2) at distance 1. Every neighbour already has a distance, so nothing new is queued. (2,1) was already reached by an earlier cell in the queue, with the same distance 2, so it is left alone (grey dashed arrow).
dist012000010102121queueemptypop (2,1) → nothing new
popped(2,1)distance 2
newnoneall neighbours set
queue0cells waiting
Pop (2,1) at distance 2. Every neighbour already has a distance, so nothing new is queued.
dist012000010102121queueemptyqueue empty → return dist
answer[[0,0,0],[0,1,0],[1,2,1]]distance to the nearest 0
Done. The queue always holds cells of distance d before cells of distance d + 1, so the first time a cell is reached is from its nearest 0. Each cell was queued once: O(m × n).
05

Common pitfalls

Running a BFS from every 1

✗ Wrong
for r, c in ones:
    dist[r][c] = bfs_to_nearest_zero(r, c)
✓ Right
for r, c in zeros:
    dist[r][c] = 0
    q.append((r, c))

Each search can scan most of the grid, so a grid full of 1s costs O((m·n)²), far too slow for 10⁴ cells. Starting from all 0s at once answers every cell in one search.

Using 0 to mean "not reached"

✗ Wrong
dist = [[0] * n for _ in range(m)]
...
if dist[nr][nc] == 0:
✓ Right
dist = [[-1] * n for _ in range(m)]
...
if dist[nr][nc] == -1:

A real 0 cell also has distance 0, so the search cannot tell it apart from an unvisited cell and walks back into the zeros, overwriting them.

Writing the distance when popping

✗ Wrong
r, c = q.popleft()
if seen[r][c]:
    continue
seen[r][c] = True
✓ Right
if dist[nr][nc] == -1:
    dist[nr][nc] = dist[r][c] + 1
    q.append((nr, nc))

A cell next to two queued cells gets pushed twice before either copy is popped. Marking it as you push keeps each cell in the queue once, so the queue stays at most m·n long.

06

Complexity

Time
O(m·n)
Space
O(m·n)
Every cell is pushed and popped once and checks four neighbours. The queue and dist each hold up to m·n cells.
07

01 Matrix FAQ

Can 01 Matrix be solved without a queue?

Yes, with two passes of dynamic programming. Pass one goes top-left to bottom-right and takes 1 + min(top, left) for each 1; pass two goes bottom-right to top-left and also considers 1 + min(bottom, right). It runs in O(m·n) time with no queue, but the BFS is easier to get right and to explain.

Why does the Python solution use a deque?

deque.popleft() takes O(1). Popping from the front of a Python list with pop(0) shifts every remaining item, which turns the BFS into O((m·n)²) on a large grid.

How is this different from Rotting Oranges?

It is the same multi-source BFS. In Rotting Oranges the sources are the rotten oranges and the answer is the number of layers until the queue empties; here the sources are the 0s and the answer is each cell's own layer number.