class Solution {
public int[][] updateMatrix(int[][] matrix) {
int[][] dirs = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int m = matrix.length, n = matrix[0].length;
Set<int[]> starters = new HashSet<>();
Queue<int[]> queue = new LinkedList<>();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == 0) {
queue.offer(new int[]{i, j});
} else {
matrix[i][j] = Integer.MAX_VALUE;
}
}
}
int level = 0;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
int[] pos = queue.poll();
for (int[] dir : dirs) {
int x = pos[0] + dir[0];
int y = pos[1] + dir[1];
if (x >= 0 && x < m && y >= 0 && y < n && matrix[x][y] != 0) {
if (matrix[x][y] == Integer.MAX_VALUE) {
queue.add(new int[]{x, y});
matrix[x][y] = level + 1;
}
}
}
}
level++;
}
return matrix;
}
}