sagelearnai

01 Matrix

Difficulty: Medium · Pattern: Graphs (BFS / DFS) · LeetCode #542

Given an m × n binary matrix, return a matrix where each cell holds the distance to the nearest 0. Adjacent cells (up, down, left, right) are distance 1 apart.

Examples

text
[[0,0,0],        [[0,0,0],
 [0,1,0],    →    [0,1,0],
 [1,1,1]]         [1,2,1]]

Hints

  1. Running a BFS from every 1 to find its nearest 0 costs O((mn)²).
  2. Turn the problem around: start one BFS from all the 0s at once.

Approach

Multi-source BFS: put every 0 cell in the queue with distance 0, and mark the 1s as unvisited (∞). BFS outward. The first time a cell is reached, it's reached from its nearest 0, because BFS expands in order of distance and all sources start at layer 0.

This is the same technique as Rotting Oranges and Walls and Gates: when there are many sources and you need each cell's nearest one, seed the queue with all of them.

A DP alternative does two passes (top-left → bottom-right, then the reverse), taking the min of neighbors + 1. Also O(mn).

Complexity

Time: O(m·n). Space: O(m·n).

Python solution
from collections import deque

def updateMatrix(mat):
    R, C = len(mat), len(mat[0])
    dist = [[0 if mat[r][c] == 0 else -1 for c in range(C)] for r in range(R)]
    q = deque((r, c) for r in range(R) for c in range(C) if mat[r][c] == 0)
    while q:
        r, c = q.popleft()
        for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
            if 0 <= nr < R and 0 <= nc < C and dist[nr][nc] == -1:
                dist[nr][nc] = dist[r][c] + 1
                q.append((nr, nc))
    return dist
JavaScript solution
function updateMatrix(mat) {
  const R = mat.length, C = mat[0].length;
  const dist = mat.map((row) => row.map((v) => (v === 0 ? 0 : -1)));
  let q = [];
  for (let r = 0; r < R; r++) for (let c = 0; c < C; c++) if (mat[r][c] === 0) q.push([r, c]);
  for (let h = 0; h < q.length; h++) {
    const [r, c] = q[h];
    for (const [nr, nc] of [[r + 1, c], [r - 1, c], [r, c + 1], [r, c - 1]]) {
      if (nr >= 0 && nc >= 0 && nr < R && nc < C && dist[nr][nc] === -1) { dist[nr][nc] = dist[r][c] + 1; q.push([nr, nc]); }
    }
  }
  return dist;
}