public int[][] updateMatrix(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
int m = matrix.length, n = matrix[0].length;
int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
dfs(i, j, matrix, directions);
public void dfs(int row, int col, int[][] matrix, int[][] directions) {
int dist = Integer.MAX_VALUE;
for (int[] direction : directions) {
int nextRow = row + direction[0];
int nextCol = col + direction[1];
if (isValid(nextRow, nextCol, matrix)) {
dist = Math.min(dist, matrix[nextRow][nextCol] + 1);
if (dist != matrix[row][col]) {
for (int[] direction : directions) {
int nextRow = row + direction[0];
int nextCol = col + direction[1];
if (isValid(nextRow, nextCol, matrix)) {
dfs(nextRow, nextCol, matrix, directions);
public boolean isValid(int nextRow, int nextCol, int[][] matrix) {
return nextRow >= 0 && nextRow < matrix.length && nextCol >= 0 && nextCol < matrix[0].length;