01 Matrix Problem
Description
LeetCode Problem 542.
Given an m x n binary matrix mat, return the distance of the nearest 0 for each cell. The distance between two adjacent cells is 1.
Example 1:
Input: mat = [[0,0,0],[0,1,0],[0,0,0]]
Output: [[0,0,0],[0,1,0],[0,0,0]]
Example 2:
Input: mat = [[0,0,0],[0,1,0],[1,1,1]]
Output: [[0,0,0],[0,1,0],[1,2,1]]
Constraints:
- m == mat.length
- n == mat[i].length
- 1 <= m, n <= 10^4
- 1 <= m * n <= 10^4
- mat[i][j] is either 0 or 1.
- There is at least one 0 in mat.
Solution
Approach: Multi-Source Breadth-First Search
Running a separate BFS from every 1 to find its nearest 0 costs O((m · n)2) in the worst case. Turn the search around instead: start from all the zeros at once and grow outward.
BFS visits cells in order of distance from where it starts. If every 0 is in the queue at the beginning, with distance 0, the search first reaches all cells at distance 1 from some zero, then all cells at distance 2, and so on. So the first time a cell is reached, the distance is to its nearest zero, whichever zero that is.
- Create
dist, with0for each zero cell and-1("not reached") for each one cell. Put every zero cell in the queue. - Take cells from the queue. For each of the 4 neighbors that is still
-1, setdist[neighbor] = dist[cell] + 1and add it to the queue. - When the queue is empty, every cell has its distance. The problem guarantees at least one
0, so no cell stays at-1.
The detail that matters is setting a cell's distance when it is first queued and never changing it afterward. Because the queue holds cells in increasing distance order, that first value is already the smallest. Marking cells only when they are taken out would let the same cell be queued many times.
Complexity: O(m · n) time, since each cell is queued once and checks 4 neighbors, and O(m · n) space for dist and the queue, where m and n are the matrix dimensions.
import collections
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: not reached yet
to_visit = collections.deque()
# Start the BFS from every 0 at once: each of them is at distance 0.
for r in range(rows):
for c in range(cols):
if mat[r][c] == 0:
dist[r][c] = 0
to_visit.append((r, c))
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
while to_visit:
r, c = to_visit.popleft()
for dr, dc in directions:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and dist[nr][nc] == -1:
dist[nr][nc] = dist[r][c] + 1 # the first time a cell is reached is the shortest
to_visit.append((nr, nc))
return dist