Time complexity: O(mn) Space complexity: O(mn)
class Solution {
// BFS Approach
public int[][] updateMatrix(int[][] matrix) {
Queue<int[]> queue = new LinkedList<>();
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if (matrix[i][j] == 0) {
queue.offer(new int[]{i, j});
} else {
matrix[i][j] = Integer.MAX_VALUE;
}
}
}
int[][] dirs = {`{-1, 0},{1, 0},{0, -1},{0, 1}`};
while (!queue.isEmpty()) {
int[] cur = queue.poll();
for (int[] dir : dirs) {
int row = cur[0] + dir[0];
int col = cur[1] + dir[1];
if (row < 0 || row > matrix.length - 1 || col < 0 || col > matrix[0].length - 1) {
continue;
}
if (matrix[row][col] <= matrix[cur[0]][cur[1]] + 1) {
continue;
}
matrix[row][col] = matrix[cur[0]][cur[1]] + 1;
queue.offer(new int[] {row, col});
}
}
return matrix;
}
}
参考链接:https://www.cnblogs.com/grandyang/p/6602288.html
TODO
TODO