public int[][] updateMatrix(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return matrix;
}
int n = matrix.length;
int m = matrix[0].length;
int[][] res = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] == 1) {
res[i][j] = bfs(matrix, i, j);
}
}
}
return res;
}
int[] x = {1, -1, 0, 0};
int[] y = {0, 0, 1, -1};
private int bfs(int[][] matrix, int i, int j) {
int n = matrix.length;
int m = matrix[0].length;
boolean[][] visited = new boolean[n][m];
Queue<Integer> queue = new LinkedList<>();
queue.offer(i * m + j);
visited[i][j] = true;
int step = 1;
while (!queue.isEmpty()) {
int size = queue.size();
for (int s = 0; s < size; s++) {
int cur = queue.poll();
int curi = cur / m;
int curj = cur % m;
for (int k = 0; k < 4; k++) {
int nexti = curi + x[k];
int nextj = curj + y[k];
if (inBound(nexti, nextj, m, n) && matrix[nexti][nextj] == 0) {
return step;
}
if (inBound(nexti, nextj, m, n) && !visited[nexti][nextj] && matrix[nexti][nextj] == 1) {
queue.offer(nexti * m + nextj);
}
}
}
step++;
}
return step;
}
private boolean inBound(int i, int j, int m, int n) {
if (i < 0 || j < 0 || i >= n || j >= m) {
return false;
} else {
return true;
}
}