01 Matrix

Distance from every cell to the nearest 0 — multi-source BFS.

Medium
Time O(m * n) Space O(m * n)
LeetCode
5 min read
dp bfs grid

Problem#

For each cell, return its distance (Manhattan) to the nearest 0.

Examples#

  • [[0,0,0],[0,1,0],[1,1,1]][[0,0,0],[0,1,0],[1,2,1]]

Constraints#

  • 1 <= m, n <= 10^4.

Approach#

Two-pass DP — sweep top-left then bottom-right, propagating min distance.
Multi-source BFS — enqueue every 0 initially with distance 0; expand outward.

Solution#

01 Matrix (multi-source BFS)
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
int m = mat.size(), n = mat[0].size();
vector<vector<int>> dist(m, vector<int>(n, INT_MAX));
queue<pair<int,int>> q;
for (int r = 0; r < m; ++r)
for (int c = 0; c < n; ++c)
if (mat[r][c] == 0) { dist[r][c] = 0; q.push({r, c}); }
int dr[4] = {1,-1,0,0}, dc[4] = {0,0,1,-1};
while (!q.empty()) {
auto [r, c] = q.front(); q.pop();
for (int k = 0; k < 4; ++k) {
int nr = r + dr[k], nc = c + dc[k];
if (nr < 0 || nr >= m || nc < 0 || nc >= n) continue;
if (dist[nr][nc] > dist[r][c] + 1) {
dist[nr][nc] = dist[r][c] + 1;
q.push({nr, nc});
}
}
}
return dist;
}
};

Editorial#

Multi-source BFS treats every 0 as a starting node; the first time we visit a 1, we have its shortest distance. Faster constant than two-pass DP in practice and same O(mn) asymptotic.

Complexity#

  • Time: O(m * n).
  • Space: O(m * n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.