01 Matrix

MediumBFS · Multi-Source · DP🧩 Graph BFSLeetCode #542 ↗Updated

Problem

You get an m × n binary matrix mat containing at least one 0. For every cell, compute the distance (number of up/down/left/right steps) to the closest 0, and return these distances as a matrix of the same shape.
Input[[0,0,0],[0,1,0],[0,0,0]]Output[[0,0,0],[0,1,0],[0,0,0]]
Input[[0,0,0],[0,1,0],[1,1,1]]Output[[0,0,0],[0,1,0],[1,2,1]]

1 ≤ m·n ≤ 104  ·  mat[i][j] ∈ {0, 1}  ·  at least one 0

Try it yourself

Java
class Solution {
    public int[][] updateMatrix(int[][] mat) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Reverse the search: start from all zeros at once and expand outward; the first time BFS reaches a cell is its answer. With no obstacles, two DP sweeps also work.
PatternGraph BFS

Instinct Minimum moves, fewest steps or shortest transformation where every step costs the same: spread outward level by level with a queue.

Memory hack Ripples in a pond: every ring is one step farther, so the first ring that touches the target is the answer.

Open the Graph BFS guide →

Approaches

Brute ForceCheck Every Zero (Manhattan Distance)

Time O((m·n)2)Space O(1) extra

There are no walls, so the step distance between two cells is simply their Manhattan distance |r1-r2| + |c1-c2|. For every 1, scan all cells and keep the minimum distance to a 0.

Java
public int[][] updateMatrix(int[][] mat) {
    int m = mat.length, n = mat[0].length;
    int[][] dist = new int[m][n];
    for (int r = 0; r < m; r++) {
        for (int c = 0; c < n; c++) {
            if (mat[r][c] == 0) continue;
            int best = Integer.MAX_VALUE;
            for (int i = 0; i < m; i++)
                for (int j = 0; j < n; j++)
                    if (mat[i][j] == 0) best = Math.min(best, Math.abs(i-r) + Math.abs(j-c));
            dist[r][c] = best;
        }
    }
    return dist;
}

Tiny code, but every 1 rescans the whole matrix — TLE on 104 cells.

At a glance

LevelApproachTimeSpace
Brute ForceCheck Every Zero (Manhattan Distance)O((m·n)2)O(1) extra
BetterMulti-Source BFS from All ZerosO(m·n)O(m·n)
OptimalTwo-Pass Dynamic ProgrammingO(m·n)O(1) extra
Common pitfalls
  • Searching from each 1 — O((mn)2); seed all the 0s instead.
  • Marking visited on poll, not on enqueue — duplicate entries.
  • Only one DP sweep — misses zeros below/right of a cell.
Interview tips
  • Name the trick: reverse the search, start from every 0.
  • BFS optimality: rings expand in non-decreasing distance.
  • Offer the two-sweep DP when asked to drop the queue.
Pattern
Multi-source BFS → “distance from every cell to the nearest X” on an unweighted grid.
My notes saved in this browser