Intuition
Start BFS from all 0-cells simultaneously. Each level adds 1 to the distance.
Explanation
Approach
- Initialize distance matrix: 0 for 0-cells, infinity for 1-cells.
- Enqueue all 0-cells.
- BFS: for each cell, update neighbors' distance if shorter path found.
Complexity
- Time: O(m*n)
- Space: O(m*n)
Implementation
import java.util.*;
class Solution {
public int[][] updateMatrix(int[][] mat) {
int rows = mat.length, cols = mat[0].length;
int[][] dist = new int[rows][cols];
Queue<int[]> queue = new LinkedList<>();
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (mat[r][c] == 0) {
dist[r][c] = 0;
queue.add(new int[]{r, c});
} else {
dist[r][c] = Integer.MAX_VALUE;
}
}
}
int[][] dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
while (!queue.isEmpty()) {
int[] cell = queue.poll();
int r = cell[0], c = cell[1];
for (int[] d : dirs) {
int nr = r + d[0], nc = c + d[1];
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && dist[nr][nc] > dist[r][c] + 1) {
dist[nr][nc] = dist[r][c] + 1;
queue.add(new int[]{nr, nc});
}
}
}
return dist;
}
}