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 * nis at most 10⁴, so the answer should touch each cell a constant number of times.
- 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.
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.
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.
Approach
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.
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.
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.
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.
Code in Python, C++ and Java
dist with -1 first, so "not reached yet" can never be confused with a real distance of 0.dist with -1 first, so "not reached yet" can never be confused with a real distance of 0.Common pitfalls
Running a BFS from every 1
for r, c in ones:
dist[r][c] = bfs_to_nearest_zero(r, c)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"
dist = [[0] * n for _ in range(m)] ... if dist[nr][nc] == 0:
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
r, c = q.popleft()
if seen[r][c]:
continue
seen[r][c] = Trueif 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.
Complexity
dist each hold up to m·n cells.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.