share my java two point solution! Really Simple, no need DFS or BFS!


  • 0
    T
    public class Solution {
        public int[][] updateMatrix(int[][] matrix) {
           int[][] res=new int[matrix.length][matrix[0].length];
           
           for(int i=0;i<res.length;i++){
               Arrays.fill(res[i],Integer.MAX_VALUE);
           }
            
           for(int i=0;i<matrix.length;i++){
                for(int j=0;j<matrix[0].length;j++){
                    if(matrix[i][j]==0){
                        res[i][j]=0;
                    }else if(matrix[i][j]!=0){
                        if(i>0&&res[i-1][j]!=Integer.MAX_VALUE){
                            res[i][j]=Math.min(res[i][j],res[i-1][j]+1);
                        }
                        if(j>0&&res[i][j-1]!=Integer.MAX_VALUE){
                            res[i][j]=Math.min(res[i][j],res[i][j-1]+1);
                        }
                    }
                }
            }
            
            for(int i=matrix.length-1;i>=0;i--){
                for(int j=matrix[0].length-1;j>=0;j--){
                    if(matrix[i][j]!=0){
                        if(i<matrix.length-1){
                            res[i][j]=Math.min(res[i][j],res[i+1][j]+1);
                        }
                        if(j<matrix[0].length-1){
                            res[i][j]=Math.min(res[i][j],res[i][j+1]+1);
                        }
                    }
                }
            }
            
            return res;
        }
        
        
    }
             
    
    
    

Log in to reply
 

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