Clean and concise Java in-place solution beats 99.7%


  • 0
    X
    public class Solution {
        public int[][] updateMatrix(int[][] matrix) {
            for(int i=0; i<matrix.length; i++){
                for(int j=0; j<matrix[0].length; j++){
                    if(matrix[i][j] != 0){
                        int up = i>0 ? matrix[i-1][j]: 30000;
                        int left = j>0 ? matrix[i][j-1]: 30000;
                        matrix[i][j] = Math.min(up, left) + 1;
                    }
                    spread(matrix, i-1, j, matrix[i][j]+1);
                    spread(matrix, i, j-1, matrix[i][j]+1);
                }
            }
            return matrix;
        }
        
        private void spread(int[][] matrix, int i, int j, int val){
            if(i<0 || j<0)  return;
            if(matrix[i][j] > val){
                matrix[i][j] = val;
                spread(matrix, i-1, j, matrix[i][j]+1);
                spread(matrix, i, j-1, matrix[i][j]+1);
            }
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.